【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();
相关推荐
刘海东刘海东几秒前
结构型智能科技的关键可行性——信息型智能向结构型智能的转变(修改提纲)
人工智能·算法·机器学习
2301_8050545612 分钟前
Python训练营打卡Day59(2025.7.3)
开发语言·python
**梯度已爆炸**22 分钟前
NLP文本预处理
人工智能·深度学习·nlp
uncle_ll26 分钟前
李宏毅NLP-8-语音模型
人工智能·自然语言处理·语音识别·语音模型·lm
Liudef0626 分钟前
FLUX.1-Kontext 高效训练 LoRA:释放大语言模型定制化潜能的完整指南
人工智能·语言模型·自然语言处理·ai作画·aigc
pumpkin8451427 分钟前
Rust 调用 C 函数的 FFI
c语言·算法·rust
静心问道28 分钟前
大型语言模型中的自动化思维链提示
人工智能·语言模型·大模型
万千思绪37 分钟前
【PyCharm 2025.1.2配置debug】
ide·python·pycharm
挺菜的38 分钟前
【算法刷题记录(简单题)003】统计大写字母个数(java代码实现)
java·数据结构·算法
mit6.82439 分钟前
7.6 优先队列| dijkstra | hash | rust
算法