【python因果推断库15】使用 sci-kit learn 模型进行回归断点分析

目录

导入数据

线性模型和主效应模型

线性模型、主效应模型和交互作用模型

使用bandwidth


python 复制代码
from sklearn.gaussian_process import GaussianProcessRegressor
from sklearn.gaussian_process.kernels import ExpSineSquared, WhiteKernel
from sklearn.linear_model import LinearRegression

import causalpy as cp
%config InlineBackend.figure_format = 'retina'

导入数据

python 复制代码
data = cp.load_data("rd")
data.head()

线性模型和主效应模型

python 复制代码
result = cp.skl_experiments.RegressionDiscontinuity(
    data,
    formula="y ~ 1 + x + treated",
    model=LinearRegression(),
    treatment_threshold=0.5,
)
fig, ax = result.plot()
python 复制代码
result.summary(round_to=3)
复制代码
Difference in Differences experiment
Formula: y ~ 1 + x + treated
Running variable: x
Threshold on running variable: 0.5

Results:
Discontinuity at threshold = 0.19
Model coefficients:
  Intercept      	         0
  treated[T.True]	      0.19
  x              	      1.23

线性模型、主效应模型和交互作用模型

python 复制代码
result = cp.skl_experiments.RegressionDiscontinuity(
    data,
    formula="y ~ 1 + x + treated + x:treated",
    model=LinearRegression(),
    treatment_threshold=0.5,
)
result.plot();

虽然我们可以看到这样做并不能很好地拟合数据,几乎肯定高估了阈值处的不连续性。

python 复制代码
result.summary(round_to=3)
复制代码
Difference in Differences experiment
Formula: y ~ 1 + x + treated + x:treated
Running variable: x
Threshold on running variable: 0.5

Results:
Discontinuity at threshold = 0.92
Model coefficients:
  Intercept        	         0
  treated[T.True]  	      2.47
  x                	      1.32
  x:treated[T.True]	     -3.11

使用bandwidth

我们处理这个问题的一种方法是使用 `bandwidth` 参数。这将只对阈值附近的一定带宽内的数据进行拟合。如果 x 是连续变量,那么模型将只对满足 的数据进行拟合。

python 复制代码
result = cp.skl_experiments.RegressionDiscontinuity(
    data,
    formula="y ~ 1 + x + treated + x:treated",
    model=LinearRegression(),
    treatment_threshold=0.5,
    bandwidth=0.3,
)

result.plot();

我们甚至可以走得更远,只为接近阈值的数据拟合截距。但很明显,这将涉及更多的估计误差,因为我们使用的数据较少。

python 复制代码
result = cp.skl_experiments.RegressionDiscontinuity(
    data,
    formula="y ~ 1 + treated",
    model=LinearRegression(),
    treatment_threshold=0.5,
    bandwidth=0.3,
)

result.plot();
相关推荐
绒绒毛毛雨2 分钟前
Advancing Table Understanding of Large Language Models via Feature Re-ordering
人工智能·语言模型·自然语言处理
Toky丶4 分钟前
【文献阅读】Optimum Quanto:量化工作流与数学公式整合笔记
人工智能·深度学习·机器学习
橙露5 分钟前
李一舟人工智能 2.0 视频分享:解锁 AI 时代核心竞争力
人工智能
Brian Xia6 分钟前
从 0 开始手写 AI Agent 框架:nano-agentscope(二)框架搭建
人工智能·python·ai
2503_946971866 分钟前
【Virtualization/AGI】2026年度全沉浸式虚拟化架构与AGI沙箱逃逸基准索引 (Benchmark Index)
人工智能·网络安全·系统架构·数据集·元宇宙
guygg888 分钟前
经典信道估计MATLAB实现(含LSMMSE算法)
深度学习·算法·matlab
易晨 微盛·企微管家12 分钟前
2026连锁品牌SCRM系统最新排名:企业微信生态下微盛·企微管家领跑
人工智能·企业微信
写代码的【黑咖啡】16 分钟前
深入了解 Python 中的 Scikit-learn:机器学习的强大工具
python·机器学习·scikit-learn
新知图书24 分钟前
FastGPT工作流的节点
人工智能·fastgpt·ai agent·智能体·大模型应用开发
乾元24 分钟前
网络切片的自动化配置与 SLA 保证——5G / 专网场景中,从“逻辑隔离”到“可验证承诺”的工程实现
运维·开发语言·网络·人工智能·网络协议·重构