【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();
相关推荐
MicroTech202512 小时前
微算法科技(NASDAQ :MLGO)量子增强区块链联邦学习:基于量子拜占庭协议的技术革新
科技·算法·区块链
Ztop12 小时前
一文说清ChatGPT Pro 5x 和 20x 区别,以及国内如何升级ChatGPT Pro 最新教程
人工智能·gpt·chatgpt
AI品信智慧数智人12 小时前
AI赋能景区|山东品信智慧科技,解锁文旅数字化新范式✨
人工智能·科技·旅游
码云数智-大飞12 小时前
CSS 优先级详解:告别样式冲突,掌控网页“层叠”艺术
人工智能·python·tensorflow
山河君12 小时前
从后验到先验:语音信噪比估计与DD算法详解
算法·音视频·语音识别·信号处理
墨染天姬12 小时前
【AI】稀疏注意力机制
人工智能
小白跃升坊12 小时前
1Panel AI 终端:用自然语言,把 Linux 运维变简单
人工智能·ai·aigc·aiagent·openclaw
迦南的迦 亚索的索12 小时前
PYTHON_DAY21_数据分析
开发语言·python·数据分析
阿Y加油吧12 小时前
栈的经典应用:字符串解码 & 每日温度 深度解析
数据结构·python·算法
想你依然心痛12 小时前
TinyVue 3.0 与 AI 协同开发指南:从组件设计到智能体编排
人工智能·ai·组件·智能体·tinyvue