【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();
相关推荐
Coder_Boy_几秒前
基于SpringAI的智能AIOps项目: 业务流程与规则规范(企业级)
人工智能·spring·spring cloud
无限码力31 分钟前
华为OD技术面真题 - Python开发 -3
python·华为od·华为od技术面真题·华为od面试八股文·华为od面试python八股文·华为od技术面八股真题
0思必得032 分钟前
[Web自动化] Requests模块响应的内容
运维·前端·python·自动化·html·web自动化
小王毕业啦36 分钟前
2011-2022年 国内光伏电站遥感矢量数据
大数据·人工智能·数据挖掘·数据分析·数据统计·社科数据·实证数据
XLYcmy37 分钟前
高级密码猜测生成器AdvancedPasswordGenerator密码生成器程序详细分析
开发语言·python·算法·网络安全·开发工具·源代码·口令安全
才不做选择40 分钟前
基于 YOLOv8 的水果智能识别系统
python·yolo·目标检测·机器学习·计算机视觉
Deepoch1 小时前
智能赋能新范式:Deepoc开发板重塑仓储物流产业生态
人工智能·具身模型·deepoc·物流机器人
the4thone1 小时前
AI基础 笔记
人工智能·笔记
Edward.W1 小时前
Python实现人物剪影转ASCII艺术生成器
开发语言·python
天天进步20151 小时前
Python全栈项目--校园智能停车管理系统
开发语言·python