机器学习数据分析【免费下载链接】dowhyDoWhy is a Python library for causal inference that supports explicit modeling and testing of causal assumptions. DoWhy is based on a unified language for causal inference, combining causal graphical models and potential outcomes frameworks.项目地址https://gitcode.com/gh_mirrors/do/dowhy点击查看免费下载导读本文讲解 DoWhy 因果推断库中的中介分析Mediation Analysis能力如何把总因果效应拆解为自然直接效应Natural Direct Effect, NDE与自然间接效应Natural Indirect Effect, NIE从而量化某个特定的因果通路到底传递了多少影响。你将掌握完整的实操流程——从构造带中介变量的数据集、建立因果模型、以estimand_type指定中介估计目标到用mediation.two_stage_regression方法完成两阶段估计并理解其背后的识别逻辑与源码实现。本文内容以 中介分析文档 为主体结合 两步回归估计器源码、识别器源码 与配套 示例 notebook 展开。一、什么是中介分析把效应拆成直接与间接两条路在因果图中处理变量 v0 对结果 y 的影响往往不止一条通路。以文档使用的典型图结构为例自然直接效应NDE经由路径v0 - y产生的效应即不经过任何中介变量的直接作用自然间接效应NIE经由路径v0 - FD0 - y产生的效应由中介变量 FD0frontdoor 变量传递。总效应total effect由这两部分构成TE NDE NIE。中介分析的意义在于它可以帮助研究者回答该影响是通过哪条具体通路传递的这一问题——例如某项营销活动对销量的影响有多少是直接促成购买直接效应又有多少是通过改变用户认知或注册状态等中间环节间接实现的间接效应。文档中给出的定义性描述如下详见 mediation_analysis.rstNatural direct effectEffect due to the path v0-yNatural indirect effectEffect due to the path v0-FD0-ymediated by FD0更严谨的数学定义可参考 Judea Pearl 的论文Interpretation and Identification of Causal Mediation文档中引用的 UCLA 技术报告。二、识别Identification用 estimand_type 指定中介目标DoWhy 的中介分析建立在标准流程model - identify_effect - estimate_effect之上。关键在于identify_effect的estimand_type参数——通过指定nonparametric-nde或nonparametric-nie识别器会为目标效应构造对应的可识别表达式estimand而不是默认的总体平均效应。# 自然直接效应nde identified_estimand_nde model.identify_effect(estimand_typenonparametric-nde, proceed_when_unidentifiableTrue) print(identified_estimand_nde) # 自然间接效应nie identified_estimand_nie model.identify_effect(estimand_typenonparametric-nie, proceed_when_unidentifiableTrue) print(identified_estimand_nie)2.1 参数说明与源码依据estimand_typenonparametric-nde/nonparametric-nie这两个字符串是 EstimandType 枚举 中NONPARAMETRIC_NDE与NONPARAMETRIC_NIE的取值。识别器据此决定对目标效应执行哪套识别流程。proceed_when_unidentifiableTrue与 DoWhy 其他识别调用一致当无法严格识别目标效应时仍然继续返回一个可能带假设的estimand 对象方便用户查看识别输出而不是直接抛异常终止流程。从源码看识别阶段会做三件与中介相关的工作auto_identifier.pyidentify_mediationauto_identifier.py枚举所有位于从处理到结果的某条有向路径上、且在其上条件化能够阻断该路径的变量即候选中介变量。测试 test_causal_graph.py 验证了并行中介场景当图结构为D - M1 - Y与D - M2 - Y并存时nonparametric-nie识别出的get_mediator_variables()同时包含 M1 与 M2。identify_mediation_first_stage_confoundersauto_identifier.py对处理 - 中介这一段做 backdoor 识别得到第一阶段的混杂调整集。identify_mediation_second_stage_confoundersauto_identifier.py对中介 - 结果这一段做 backdoor 识别得到第二阶段的混杂调整集。这两组混杂集被存入IdentifiedEstimand对象的mediation_first_stage_confounders与mediation_second_stage_confounders属性identified_estimand.py并在后续估计阶段被两步回归估计器读取使用。同时识别结果中还会带上get_mediator_variables()返回的中介变量列表identified_estimand.pyprint出来的 estimand 字符串会以 Estimand type: nonparametric-nde / nonparametric-nie 开头identified_estimand.py。2.2 识别策略的本质化整为零中介效应的识别并没有引入全新的复杂公式而是把处理 v0 经中介 FD0 到结果 y的链条拆成两段独立的 backdoor 问题第一阶段估计v0 - FD0的效应需要调整的是处理到中介路径上的混杂第二阶段估计FD0 - y的效应需要调整的是中介到结果路径上的混杂。两阶段效应之积即为自然间接效应。这种把中介估计转换为一系列 backdoor 效应估计的思路正是 示例 notebook 中明确描述的估计器设计原理。三、估计Estimationmediation.two_stage_regression当前 DoWhy 为 NDE/NIE 提供的估计方法是mediation.two_stage_regression两步回归法。它的用法与frontdoor.two_stage_regression同源均落在 TwoStageRegressionEstimator 上只是通过identifier_method mediation分支进入中介逻辑。3.1 完整可运行的估计代码文档原样继承import dowhy.causal_estimators.linear_regression_estimator # ---- 自然间接效应 NIE ---- causal_estimate_nie model.estimate_effect( identified_estimand_nie, method_namemediation.two_stage_regression, confidence_intervalsFalse, test_significanceFalse, method_params{ first_stage_model: dowhy.causal_estimators.linear_regression_estimator.LinearRegressionEstimator, second_stage_model: dowhy.causal_estimators.linear_regression_estimator.LinearRegressionEstimator }) print(causal_estimate_nie) # ---- 自然直接效应 NDE ---- causal_estimate_nde model.estimate_effect( identified_estimand_nde, method_namemediation.two_stage_regression, confidence_intervalsFalse, test_significanceFalse, method_params{ first_stage_model: dowhy.causal_estimators.linear_regression_estimator.LinearRegressionEstimator, second_stage_model: dowhy.causal_estimators.linear_regression_estimator.LinearRegressionEstimator }) print(causal_estimate_nde)3.2 关键参数详解参数含义默认值 / 取值建议method_name估计方法名遵循识别方法.估计方法约定必须为mediation.two_stage_regressionconfidence_intervals是否计算置信区间可传False、True或bootstrap文档示例用False若需区间可用True/bootstrap配合num_simulations、sample_size_fractiontest_significance是否做显著性检验可传False、True或bootstrap文档示例用Falsemethod_params[first_stage_model]第一阶段估计器类估计处理 - 中介的效应默认LinearRegressionEstimator见源码 two_stage_regression_estimator.py 的DEFAULT_FIRST_STAGE_MODELmethod_params[second_stage_model]第二阶段估计器类估计中介 - 结果的效应默认LinearRegressionEstimatorDEFAULT_SECOND_STAGE_MODEL关于test_significance与confidence_intervals的更细语义源码 docstring 有明确说明two_stage_regression_estimator.py两者均可传bootstrap以使用自助法test_significance的 bootstrap 支持可选参数num_null_simulationsconfidence_intervals的 bootstrap 支持num_simulations与sample_size_fraction。3.3 两步回归的底层计算逻辑源码级从 estimate_effect 的实现可以还原完整计算链条第一阶段first_stage_estimate用first_stage_model估计处理 v0 对中介 FD0 的效应。注意此时估计器的目标变量被替换为中介变量——在 fit 中mediation分支会把_first_stage_model._target_estimand.outcome_variable设为中介名。第二阶段second_stage_estimate用second_stage_model估计中介 FD0 对结果 y 的效应估计器的处理变量被替换为中介名two_stage_regression_estimator.py。NIE 合成natural_indirect_effect first_stage_estimate.value * second_stage_estimate.value符号表达式为nie_symbolic ( first_stage_symbolic )*( second_stage_symbolic )two_stage_regression_estimator.py。NDE 合成当目标为NONPARAMETRIC_NDE时额外用_second_stage_model_nde以第二段混杂集调整的副本估计器算出总效应total_effect_estimate然后natural_direct_effect total_effect_estimate.value - natural_indirect_effect即NDE TE - NIEtwo_stage_regression_estimator.py。此外估计器的构造函数会读取识别阶段产出的两个混杂集第一阶段用mediation_first_stage_confounders作为 backdoor 变量集第二阶段用mediation_second_stage_confounderstwo_stage_regression_estimator.py从而完成中介估计 - 两段 backdoor 估计的转换。3.4 使用约束来自源码的明确限制目前两步回归只支持线性模型类 docstring 明确说明 Currently only supports a linear model for the effectstwo_stage_regression_estimator.py只支持单一处理变量多处理变量会抛出ValueErrortwo_stage_regression_estimator.py只支持单一中介变量多个中介变量同样会抛出ValueErrortwo_stage_regression_estimator.py若图中没有中介变量估计会报错 No mediator variable present. Two stage regression is not applicabletwo_stage_regression_estimator.py。四、端到端实操从数据集构造到效应验证配套的 dowhy_mediation_analysis.ipynb 给出了完整示例下面按步骤串联。4.1 Step 1构造带中介的数据集并建模使用 linear_dataset 生成一个基于 frontdoor 准则的线性数据集处理对结果没有直接效应全部效应都经由中介变量 FD0 传递这正好让 NDE 的真值为 0便于验证估计器是否正确。import dowhy dowhy.enable_notebook_rendering() import numpy as np import pandas as pd from dowhy import CausalModel import dowhy.datasets data dowhy.datasets.linear_dataset( 10, # beta处理系数 num_common_causes1, # 1 个共同混杂 W0 num_samples10000, num_instruments0, # 无工具变量 num_effect_modifiers0, # 无效应修饰变量 num_treatments1, num_frontdoor_variables1, # 1 个中介变量 FD0 treatment_is_binaryFalse, # 连续处理 outcome_is_binaryFalse) df data[df] print(df.head()) model CausalModel(df, data[treatment_name], data[outcome_name], data[gml_graph], missing_nodes_as_confoundersTrue) model.view_model()linear_dataset返回字典中包含df、treatment_name、outcome_name、gml_graph以及真实 ATEdata[ate]等元信息datasets.py。生成逻辑上当num_frontdoor_variables 0时中介变量按FD t cfd1 W c1_frontdoor noise生成结果按y FD cfd2 noise生成datasets.py——即处理只能通过 FD 影响 y直接边被刻意置零。4.2 Step 2识别 NDE 与 NIE按本文第二节的代码分别调用两次identify_effect指定nonparametric-nde与nonparametric-nie并print查看识别出的估计表达式与假设。4.3 Step 3两步回归估计并对照真值运行第三节的估计代码后print(causal_estimate_nie.value, data[ate])notebook 中说明由于模拟数据把直接效应设为零ate参数实际上就是经由中介传递的间接效应大小估计出的 NIE 值应当接近data[ate]。随后估计 NDE预期结果接近 0——因为数据生成机制里根本没有v0 - y的直接边。print(causal_estimate_nde)这种构造已知真值的数据 - 估计 - 对照真值的做法是验证中介分析实现正确性的标准方式也方便读者确认自己对 NDE/NIE 的理解。4.4 Step 4关于反驳Refutation示例 notebook 的第 4 步标注为TODO即中介分析的反驳验证尚未在示例中展开。在实战中读者可沿用 DoWhy 通用反驳工具如 placebo 处理、随机共同原因等参见 causal_refuters对 NDE/NIE 估计做稳健性检查。五、方法与原理小结环节关键 API / 参数底层实现位置指定目标效应estimand_typenonparametric-nde/nonparametric-nieEstimandType中介识别identify_mediation 两段混杂识别auto_identifier.py估计方法method_namemediation.two_stage_regressionTwoStageRegressionEstimatorNIE 公式第一阶段效应 × 第二阶段效应two_stage_regression_estimator.pyNDE 公式总效应 − NIEtwo_stage_regression_estimator.py核心要点回顾中介分析回答效应走哪条路NDE 度量v0 - y的直接通路NIE 度量v0 - FD0 - y的间接通路且TE NDE NIE识别靠 estimand_typenonparametric-nde/nonparametric-nie让识别器自动找出中介变量并为两段路径分别计算 backdoor 调整集估计靠两步回归mediation.two_stage_regression把中介估计转化为两段 backdoor 线性回归NIE 一阶段效应 × 二阶段效应NDE 总效应 − NIE当前约束仅支持线性模型、单处理变量、单中介变量未来计划引入 Imai-Keele-Yamamoto (2010) 的非参数蒙特卡洛方法notebook 中已注明。掌握了这套流程你就可以在自己的因果图中用 DoWhy 把总效应分解成直接与间接两部分量化特定通路的贡献——例如判断营销投入究竟是通过改变中介状态如注册、加购间接影响转化还是存在不依赖中介的直接拉动。赞分享机器学习数据分析【免费下载链接】dowhyDoWhy is a Python library for causal inference that supports explicit modeling and testing of causal assumptions. DoWhy is based on a unified language for causal inference, combining causal graphical models and potential outcomes frameworks.项目地址https://gitcode.com/gh_mirrors/do/dowhy点击查看免费下载相关推荐DoWhy 自然实验估计使用工具变量与回归断点方法估计平均因果效应DoWhy 自然实验估计使用工具变量与回归断点方法估计平均因果效应 导读 在因果推断中当存在未观测混杂因素、常规的后门调整无法使用时 自然实验natur机器学习数据分析如何在3分钟内将B站视频变成结构化笔记BiliTools AI总结功能详解如何在3分钟内将B站视频变成结构化笔记BiliTools AI总结功能详解 你是否曾经面对B站海量学习视频感到无从下手收藏夹里堆满了教程却永远没时间看Bi桌面应用音视频OpenSRE 实战以 checkout-high-latency 为模板构建 AI SRE 的高延迟事故排查 RunbookOpenSRE 实战以 checkout high latency 为模板构建 AI SRE 的高延迟事故排查 Runbook 导读 OpenSREBui机器学习数据分析上一篇mobilenetv2_050.lamb_in1k模型原理解析轻量级架构如何实现高效特征提取下一篇黑苹果休眠问题完美解决gh_mirrors/ha/Hackintosh项目方案创作声明:本文部分内容由AI辅助生成(AIGC),仅供参考
