【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();
相关推荐
kisshuan12396几秒前
使用YOLO11-C3k2-VSSD模型实现脐橙病害智能检测与分类,从数据准备到模型训练的完整指南
人工智能·分类·数据挖掘
此剑之势丶愈斩愈烈几秒前
mybatis-plus乐观锁
开发语言·python·mybatis
vibag几秒前
LangGraph全家桶使用
python·语言模型·langchain·大模型·langgraph
ws2019071 分钟前
湾区引擎轰鸣:AUTO TECH China 2026广州汽车零部件展何以撬动全球汽车供应链?
大数据·人工智能·科技·汽车
BitaHub20242 分钟前
文献分享 | Meta CLIP 2 来了:打破多语言瓶颈的全球化视觉-语言模型
人工智能·语言模型·自然语言处理
2501_941805932 分钟前
在苏黎世智慧医疗场景中构建影像实时分析与高并发诊断辅助平台的工程设计实践经验分享
人工智能
星火开发设计2 分钟前
折半插入排序原理与C++实现详解
java·数据结构·c++·学习·算法·排序算法·知识
勘察加熊人3 分钟前
python实现批量中英文文件翻译
开发语言·windows·python
电商API_180079052474 分钟前
获取淘宝商品视频API教程:从授权到落地实战
大数据·数据库·人工智能·数据分析·音视频
wyz1915 分钟前
第19章 数据治理的发展趋势
大数据·人工智能·数据治理·数据要素·数据资源