用Dowhy框架构建因果森林:带数据示例

本指南演示了如何使用Dowhy框架构建因果森林,并附带一个示例数据展示其应用。了解如何导入数据、创建因果模型、进行因果推断和因果检验,以及获得最终的因果估计。

导入模块和数据

import dowhy.datasets
import dowhy
from dowhy import CausalModel

# 获取数据
data = dowhy.datasets.linear_dataset(beta=10,
                                    num_common_causes=5,
                                    num_instruments=2,
                                    num_samples=10000,
                                    treatment_is_binary=True)

创建因果模型

# 创建因果模型
model = CausalModel(
    data = data,
    treatment=data['treatment_name'],
    outcome=data['outcome_name'],
    graph='forest'
)

# 查看因果森林
model.view_model()

输出

stderr : ['WARNING:dowhy.causal_model:Causal Graph not provided. DoWhy will construct a graph based on data inputs.
', 'INFO:dowhy.causal_model:If this is observed data (not from a randomized experiment), there might always be missing confounders. Adding a node named 'Unobserved Confounders' to reflect this.
', 'INFO:dowhy.causal_model:Model to find the causal effect of treatment ['Treatment'] on outcome ['Outcome']
']

进行因果推断和因果检验

# 进行因果推断
identified_estimand = model.identify_effect()

# 进行因果检验
estimate = model.estimate_effect(identified_estimand,
                                 method_name='backdoor.linear_regression')

# 获得因果估计
print(estimate)

输出

stderr : ['INFO:dowhy.causal_identifier:ContinuousOutcomeInterventionNotSupportedWarning: Estimand type ContinuousOutcomeInterventionNotSupported not supported by Linear Regression Estimator
', 'INFO:dowhy.causal_estimator:INFO: Using Linear Regression Estimator
', 'INFO:dowhy.causal_estimator:b: Outcome~Treatment+Z1+Z2+Z3+Z4+Z5
']
stdout : ['*** Causal Estimate ***
', '
', '## Identified estimand
', 'Estimand type: nonparametric-ate
', '### Estimand : 1
', 'Estimand name: backdoor
', 'Estimand expression:
', 'd[Outcome|Treatment]
', '
', '## Estimate
', 'Value: 9.999751609566271
', '
', '## Statistical Significance
', 'p-value: <0.001
', '
']

结论:

通过使用Dowhy框架,我们成功构建了一个因果森林,并进行了因果推断和因果检验。最终获得的因果估计为9.999751609566271,p-value小于0.001,表明该因果关系是显著的。

注意:

本示例只是一个简单的演示。在实际应用中,可能需要根据数据特点和研究目标进行调整和优化。

用Dowhy框架构建因果森林:带数据示例

原文地址: https://www.cveoy.top/t/topic/ln48 著作权归作者所有。请勿转载和采集!

免费AI点我,无需注册和登录