入门指南#
安装#
最简单的安装方式是通过 pip 或 conda:
pip install dowhy
conda install -c conda-forge dowhy
更多安装场景和说明可以在安装中找到。
“你好因果推理世界”#
在本节中,我们将展示DoWhy的“Hello world”版本。DoWhy基于一个简单的统一语言进行因果推断,统一了两个强大的框架,即图形因果模型(GCM)和潜在结果(PO)。它使用基于图的标准和do-calculus来建模假设并识别非参数因果效应。
为了让你入门,我们从DoWhy提供的众多功能中介绍两个功能。
效果推断#
为了进行效果估计,DoWhy 主要转向基于潜在结果的方法。为此,DoWhy 提供了一个简单的四步流程,包括建模因果模型、识别、估计和反驳:
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用于回答这些因果问题,遵循以下简单的三步配方:
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知识发现与数据挖掘2018会议
微软研究院提供的因果推理四个步骤及其对机器学习影响的视频介绍: 因果推理基础及其对机器学习的影响
PDF书籍 因果推理要素
即将出版的书籍草稿章节:因果推理:基础与机器学习应用
一篇博客文章描述了DoWhy通过图形因果模型进行根本原因分析的一种算法:新方法识别统计异常值的根本原因