【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();
相关推荐
2601_95575962几秒前
ClaudeAPI企业运营数据周报怎么做
大数据·人工智能
Anita-lee1 分钟前
北美智能电动牙刷市场退货率控制与海外售后服务体系构建指南
大数据·人工智能
XR1234567886 分钟前
办公大楼组网选型决策树:TCO 与三大品牌优劣对比总结
算法·决策树·机器学习
QYRdata9 分钟前
24.7%年复合增长率!工业元宇宙平台2026-2032年发展预期明确
大数据·网络·人工智能
武汉誉天9 分钟前
AI运维课程都学什么内容?
运维·人工智能
做萤石二次开发的哈哈12 分钟前
萤石蓝海AIoT一站式工作台新增海康消防烟感接入:多端智慧消防应用一站生成
人工智能·物联网·萤石开放平台·蓝海aiot一站式工作台·aiot开发·海康消防烟感·报警推送
cd_9492172113 分钟前
AI生成的纹理需要在Substance Painter里继续修改吗?PBR材质精修与角色纹理流程
人工智能·材质·substance painter
阳明山水23 分钟前
Mamba路径如何建模长程时序依赖
人工智能·深度学习·算法·机器学习·架构
今天测什么27 分钟前
零基础教程:用豆包快速生成动漫视频
人工智能·科技·ai·动漫
MartinYeung534 分钟前
[论文学习]大语言模型越狱的机械可解释性:基于内部归因图的分析
人工智能·学习·语言模型