在 Python 中做合成控制分析,推荐用什么包或者方法?为什么?
- User
在 Python 中做合成控制分析,推荐用什么包或者方法?为什么?
Assistant
Other models, same or similar prompt
Responses were produced in different, uncontrolled contexts (system prompts, settings, prior turns). This is not a benchmark.
在 Python 中做合成控制分析,推荐用什么包或者方法?为什么?
Responses were produced in different, uncontrolled contexts (system prompts, settings, prior turns). This is not a benchmark.
在 Python 中进行合成控制分析 (Synthetic Control Analysis, SCA),有几个推荐的包和方法,它们各有侧重。选择哪个取决于你的具体需求、数据量以及你对分析深度和灵活性的要求。
scpi (Synthetic Control with Permutation Inference)
pip install scpipysyncon (PySyntheticControl)
PySynth 的一个更现代和维护更好的版本。
pysyncon 的 API 设计相对简洁,对于初学者来说,是学习和实现标准合成控制的良好起点。pysyncon 是一个不错的选择。pip install pysyncon手动实现 (使用 scipy.optimize 或 cvxpy)
scipy.optimize.minimize (配合适当的约束) 或者更专业的优化库 cvxpy 来解决这个优化问题。cvxpy 对于处理凸优化问题(如带L1/L2正则化的最小二乘)非常强大。scpi: 强调统计推断的严谨性和功能的全面性。合成控制的效果评估不仅仅是看图形,更要看处理效应是否具有统计显著性。scpi 内置的置换检验极大地简化了这一关键步骤,使其成为进行严肃学术研究或商业决策的首选。此外,它对更复杂的合成控制方法(如广义合成控制)的支持,使其能应对更广泛的数据场景。
pysyncon: 强调易用性和对核心算法的忠实实现。如果你的需求是快速上手,对标准的合成控制方法有一个直观的了解和实现,pysyncon 是一个很好的工具。它提供了一个清晰的 API,让你能够专注于数据准备和结果解释。
手动实现: 强调灵活性和深度理解。当你需要超越现有包的功能,或者对合成控制算法的内部工作原理有非常深入的兴趣时,手动实现是唯一途径。它迫使你理解每一个数学细节和优化步骤。
scpi 包)import pandas as pd
import numpy as np
from scpi import scpi
import matplotlib.pyplot as plt
# 1. 模拟数据 (真实分析中请使用你的实际数据)
np.random.seed(42)
n_units = 20
n_time_pre = 50
n_time_post = 20
treatment_time = n_time_pre
# 创建一个处理单位 (unit 0) 和 19 个控制单位
data = []
for unit_id in range(n_units):
base_outcome = np.sin(np.linspace(0, 3 * np.pi, n_time_pre + n_time_post)) * 10 + np.random.normal(0, 1, n_time_pre + n_time_post)
covariate1 = np.random.rand(n_time_pre + n_time_post) * 5 + np.random.normal(0, 0.5)
covariate2 = np.cos(np.linspace(0, 2 * np.pi, n_time_pre + n_time_post)) * 3 + np.random.normal(0, 0.3)
if unit_id == 0: # treated unit
# 在处理后增加一个处理效应
treatment_effect = np.concatenate([np.zeros(n_time_pre),
np.linspace(0, 5, n_time_post) + np.random.normal(0, 0.5, n_time_post)])
outcome = base_outcome + treatment_effect
else: # control units
outcome = base_outcome
for t in range(n_time_pre + n_time_post):
data.append({
'unit': f'Unit_{unit_id}',
'time': t,
'outcome': outcome[t],
'covariate1': covariate1[t],
'covariate2': covariate2[t]
})
df = pd.DataFrame(data)
# 标记处理单位
treated_unit = 'Unit_0'
# 2. 运行 scpi
model = scpi.SynthControl(
data=df,
outcome_col='outcome',
unit_col='unit',
time_col='time',
treated_unit=treated_unit,
treatment_time=treatment_time,
covariate_cols=['covariate1', 'covariate2'], # 用于匹配的协变量
alpha=0.5 # 调整结果变量和协变量在权重优化中的重要性
)
# 拟合模型
model.fit()
# 3. 获取结果和可视化
df_results = model.get_results()
# 绘制处理组和合成对照组的趋势
fig, ax = model.plot_trends()
plt.title(f'Outcome Trends: {treated_unit} vs. Synthetic Control')
plt.show()
# 绘制处理效应
fig, ax = model.plot_treatment_effect()
plt.title(f'Treatment Effect for {treated_unit}')
plt.show()
# 4. 进行置换检验 (Placebo Test)
# 注意:这个可能需要一些时间运行,取决于 control pool 的大小和迭代次数
results_placebo = model.run_placebo_test(
n_iterations=50, # 迭代次数,实际分析中建议更多 (e.g., 500+)
plot_path=None # 可以指定保存图的路径
)
# 绘制置换检验结果 (如 RMSE 排名)
fig, ax = model.plot_rmse_ranking()
plt.title('Pre-treatment RMSE Ranking')
plt.show()
# 绘制安慰剂处理效应图
fig, ax = model.plot_placebo_effects(plot_all_units=True) # 绘制所有安慰剂的效应
plt.title('Placebo Treatment Effects')
plt.show()
# 总结和打印重要的模型信息
print("\n--- Model Summary ---")
print(f"Treated Unit: {model.treated_unit}")
print(f"Treatment Time: {model.treatment_time}")
print(f"Pre-treatment RMSE: {model.pre_treatment_rmse:.4f}")
print("\n--- Synthetic Control Weights ---")
weights_df = model.get_weights()
print(weights_df)
print("\n--- Treatment Effect (Post-treatment Mean Diff) ---")
# 估算的处理效应(处理后平均差)
post_treatment_diff_mean = model.get_treatment_effect().loc[model.treatment_time:].mean()
print(f"Average Treatment Effect (Post-treatment): {post_treatment_diff_mean:.4f}")
# 可以进一步检查 placebo_test 的详细结果
# print(results_placebo.head())
选择哪个包取决于你的项目需求:如果你需要进行严谨的、带有统计推断的合成控制分析,scpi 是最佳选择。如果你刚入门,想快速理解和实现核心逻辑,pysyncon 更简单易用。而手动实现则适合那些需要极致控制或深入学习底层机制的用户。