【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();
相关推荐
MaoziShan几秒前
CMU Subword Modeling | 22 Phonological Similarity and Cognate Detection
人工智能·语言模型·自然语言处理·分类
Greyson1几秒前
SQL如何解决GROUP BY导致查询变慢_利用覆盖索引进行优化
jvm·数据库·python
Chase_______3 分钟前
LeetCode 1456:定长子串中元音的最大数目
算法·leetcode
智星云算力3 分钟前
算力民主化的 “临界点”:RTX 5090 专属算力平台专项测评与租用实战分析
大数据·人工智能·gpu算力·智星云·gpu租用
小O的算法实验室4 分钟前
2026年IEEE IOTJ,DNA序列启发相似性驱动粒子群算法+无人机与基站部署,深度解析+性能实测
算法·论文复现·智能算法·智能算法改进
谭欣辰4 分钟前
Floyd算法:动态规划解最短路径
c++·算法·图论
m0_613856294 分钟前
html标签如何插入图片_html中img标签的正确使用方式【方法】
jvm·数据库·python
掘金安东尼4 分钟前
Cloudflare :Agent Readiness 评分来了!你的网站,AI 代理能"看懂"吗?
人工智能
计算机安禾5 分钟前
【Linux从入门到精通】第12篇:进程的前后台切换与信号控制
linux·运维·算法
我是发哥哈5 分钟前
主流AI培训机构能力横向评测:核心维度与选型要点解析
大数据·人工智能·学习·机器学习·ai·chatgpt·aigc