入门#
安装#
最简单的安装方式是通过 pip 或 conda
pip install dowhy
conda install -c conda-forge dowhy
更多安装场景和说明请参见 安装。
“因果推断世界,你好”#
在本节中,我们将展示 DoWhy 的“Hello world”版本。DoWhy 基于一种简单的统一因果推断语言,统一了两个强大的框架,即图因果模型 (GCM) 和潜在结果 (PO)。它使用基于图的标准和 do-calculus 来建模假设和识别非参数因果效应。
为了帮助您入门,我们将介绍 DoWhy 提供的众多功能中的两个。
效应推断#
对于效应估计,DoWhy 主要采用基于潜在结果的方法。为此,DoWhy 提供了一个简单的 4 步流程:建模因果模型、识别、估计和反驳。
from dowhy import CausalModel
import dowhy.datasets
# Generate some sample data
data = dowhy.datasets.linear_dataset(
beta=10,
num_common_causes=5,
num_instruments=2,
num_samples=10000)
# Step 1: Create a causal model from the data and given graph.
model = CausalModel(
data=data["df"],
treatment=data["treatment_name"],
outcome=data["outcome_name"],
graph=data["gml_graph"])
# Step 2: Identify causal effect and return target estimands
identified_estimand = model.identify_effect()
# Step 3: Estimate the target estimand using a statistical method.
estimate = model.estimate_effect(identified_estimand,
method_name="backdoor.propensity_score_matching")
# Step 4: Refute the obtained estimate using multiple robustness checks.
refute_results = model.refute_estimate(identified_estimand, estimate,
method_name="random_common_cause")
要理解这四个步骤的含义(以及为什么需要四个步骤),最好的学习地点是用户指南的估计因果效应一章。另外,您可以深入研究代码并在计算因果效应的基础示例中探索基本功能。
对于条件效应的估计,您还可以使用来自 EconML 的方法,使用相同的 API,请参见 使用 DoWhy 和 EconML 计算条件平均处理效应 (CATE)。
基于图因果模型的推断#
对于根本原因分析、点对点反事实推断、结构分析等功能,DoWhy 使用图因果模型。图因果模型的语言再次提供了多种可以回答的因果问题。DoWhy 回答这些因果问题的 API 遵循一个简单的 3 步流程如下
import networkx as nx, numpy as np, pandas as pd
from dowhy import gcm
# Let's generate some "normal" data we assume we're given from our problem domain:
X = np.random.normal(loc=0, scale=1, size=1000)
Y = 2 * X + np.random.normal(loc=0, scale=1, size=1000)
Z = 3 * Y + np.random.normal(loc=0, scale=1, size=1000)
data = pd.DataFrame(dict(X=X, Y=Y, Z=Z))
# Step 1: Model our system:
causal_model = gcm.StructuralCausalModel(nx.DiGraph([('X', 'Y'), ('Y', 'Z')]))
gcm.auto.assign_causal_mechanisms(causal_model, data)
# Step 2: Train our causal model with the data from above:
gcm.fit(causal_model, data)
# Step 3: Perform a causal analysis. For instance, root cause analysis, where we observe
anomalous_sample = pd.DataFrame(dict(X=[0.1], Y=[6.2], Z=[19])) # Here, Y is the root cause.
# ... and would like to answer the question:
# "Which node is the root cause of the anomaly in Z?":
anomaly_attribution = gcm.attribute_anomalies(causal_model, "Z", anomalous_sample)
如果您想了解更多关于此以及其他 GCM 功能的信息,我们建议从用户指南中的图因果模型建模 (GCMs)开始,或者查看图因果模型基础示例。
更多资源#
还有更多资源可用
因果推断入门教程
在 ACM Knowledge Discovery and Data Mining 2018 会议上的关于因果推断和反事实推理的综合教程
来自微软研究院的视频介绍,关于因果推断的四个步骤及其对机器学习的影响:因果推断的基础及其对机器学习的影响
PDF 书籍《因果推断要素》
即将出版的书籍草稿章节:《因果推理:基础与机器学习应用》
一篇博文,通过图因果模型描述了 DoWhy 的一种根本原因分析算法:新方法识别统计异常值的根本原因