Causal Inference

Causal Inference

Guides an AI agent to estimate cause-and-effect with propensity scoring, instrumental variables, difference-in-differences and causal graphs, with Python code.

Skill files3 files

scripts/

templates/

SKILL.md302 lines
1
---
2
name: Causal Inference
3
description: Determine cause-and-effect relationships using propensity scoring, instrumental variables, and causal graphs for policy evaluation and treatment effects
4
---
5
6
# Causal Inference
7
8
## Overview
9
10
Causal inference determines cause-and-effect relationships and estimates treatment effects, going beyond correlation to understand what causes what.
11
12
## When to Use
13
14
- Evaluating the impact of policy interventions or business decisions
15
- Estimating treatment effects when randomized experiments aren't feasible
16
- Controlling for confounding variables in observational data
17
- Determining if a marketing campaign or product change caused an outcome
18
- Analyzing heterogeneous treatment effects across different user segments
19
- Making causal claims from non-experimental data using propensity scores or instrumental variables
20
21
## Key Concepts
22
23
- **Treatment**: Intervention or exposure
24
- **Outcome**: Result or consequence
25
- **Confounding**: Variables affecting both treatment and outcome
26
- **Causal Graph**: Visual representation of relationships
27
- **Treatment Effect**: Impact of intervention
28
- **Selection Bias**: Non-random treatment assignment
29
30
## Causal Methods
31
32
- **Randomized Controlled Trials (RCT)**: Gold standard
33
- **Propensity Score Matching**: Balance treatment/control
34
- **Difference-in-Differences**: Before/after comparison
35
- **Instrumental Variables**: Handle endogeneity
36
- **Causal Forests**: Heterogeneous treatment effects
37
38
## Implementation with Python
39
40
```python
41
import pandas as pd
42
import numpy as np
43
import matplotlib.pyplot as plt
44
import seaborn as sns
45
from sklearn.linear_model import LinearRegression, LogisticRegression
46
from sklearn.preprocessing import StandardScaler
47
from scipy import stats
48
49
# Generate observational data with confounding
50
np.random.seed(42)
51
52
n = 1000
53
54
# Confounder: Age (affects both treatment and outcome)
55
age = np.random.uniform(25, 75, n)
56
57
# Treatment: Training program (more likely for younger people)
58
treatment_prob = 0.3 + 0.3 * (75 - age) / 50 # Inverse relationship with age
59
treatment = (np.random.uniform(0, 1, n) < treatment_prob).astype(int)
60
61
# Outcome: Salary (affected by both treatment and age)
62
# True causal effect of treatment: +$5000
63
salary = 40000 + 500 * age + 5000 * treatment + np.random.normal(0, 10000, n)
64
65
df = pd.DataFrame({
66
'age': age,
67
'treatment': treatment,
68
'salary': salary,
69
})
70
71
print("Observational Data Summary:")
72
print(df.describe())
73
print(f"\nTreatment Rate: {df['treatment'].mean():.1%}")
74
print(f"Average Salary (Control): ${df[df['treatment']==0]['salary'].mean():.0f}")
75
print(f"Average Salary (Treatment): ${df[df['treatment']==1]['salary'].mean():.0f}")
76
77
# 1. Naive Comparison (BIASED - ignores confounding)
78
naive_effect = df[df['treatment']==1]['salary'].mean() - df[df['treatment']==0]['salary'].mean()
79
print(f"\n1. Naive Comparison: ${naive_effect:.0f} (BIASED)")
80
81
# 2. Regression Adjustment (Covariate Adjustment)
82
X = df[['treatment', 'age']]
83
y = df['salary']
84
model = LinearRegression()
85
model.fit(X, y)
86
regression_effect = model.coef_[0]
87
88
print(f"\n2. Regression Adjustment: ${regression_effect:.0f}")
89
90
# 3. Propensity Score Matching
91
# Estimate probability of treatment given covariates
92
ps_model = LogisticRegression()
93
ps_model.fit(df[['age']], df['treatment'])
94
df['propensity_score'] = ps_model.predict_proba(df[['age']])[:, 1]
95
96
print(f"\n3. Propensity Score Matching:")
97
print(f"PS range: [{df['propensity_score'].min():.3f}, {df['propensity_score'].max():.3f}]")
98
99
# Matching: find control for each treated unit
100
matched_pairs = []
101
treated_units = df[df['treatment'] == 1].index
102
for treated_idx in treated_units:
103
treated_ps = df.loc[treated_idx, 'propensity_score']
104
treated_age = df.loc[treated_idx, 'age']
105
106
# Find closest control unit
107
control_units = df[(df['treatment'] == 0) &
108
(df['propensity_score'] >= treated_ps - 0.1) &
109
(df['propensity_score'] <= treated_ps + 0.1)].index
110
111
if len(control_units) > 0:
112
closest_control = min(control_units,
113
key=lambda x: abs(df.loc[x, 'propensity_score'] - treated_ps))
114
matched_pairs.append({
115
'treated_idx': treated_idx,
116
'control_idx': closest_control,
117
'treated_salary': df.loc[treated_idx, 'salary'],
118
'control_salary': df.loc[closest_control, 'salary'],
119
})
120
121
matched_df = pd.DataFrame(matched_pairs)
122
psm_effect = (matched_df['treated_salary'] - matched_df['control_salary']).mean()
123
print(f"PSM Effect: ${psm_effect:.0f}")
124
print(f"Matched pairs: {len(matched_df)}")
125
126
# 4. Stratification by Propensity Score
127
df['ps_stratum'] = pd.qcut(df['propensity_score'], q=5, labels=False, duplicates='drop')
128
129
stratified_effects = []
130
for stratum in df['ps_stratum'].unique():
131
stratum_data = df[df['ps_stratum'] == stratum]
132
if (stratum_data['treatment'] == 0).sum() > 0 and (stratum_data['treatment'] == 1).sum() > 0:
133
treated_mean = stratum_data[stratum_data['treatment'] == 1]['salary'].mean()
134
control_mean = stratum_data[stratum_data['treatment'] == 0]['salary'].mean()
135
effect = treated_mean - control_mean
136
stratified_effects.append(effect)
137
138
stratified_effect = np.mean(stratified_effects)
139
print(f"\n4. Stratification by PS: ${stratified_effect:.0f}")
140
141
# 5. Visualization
142
fig, axes = plt.subplots(2, 2, figsize=(14, 10))
143
144
# Treatment distribution by age
145
ax = axes[0, 0]
146
treated = df[df['treatment'] == 1]
147
control = df[df['treatment'] == 0]
148
ax.hist(control['age'], bins=20, alpha=0.6, label='Control', color='blue')
149
ax.hist(treated['age'], bins=20, alpha=0.6, label='Treated', color='red')
150
ax.set_xlabel('Age')
151
ax.set_ylabel('Frequency')
152
ax.set_title('Age Distribution by Treatment')
153
ax.legend()
154
ax.grid(True, alpha=0.3, axis='y')
155
156
# Salary vs Age (colored by treatment)
157
ax = axes[0, 1]
158
ax.scatter(control['age'], control['salary'], alpha=0.5, label='Control', s=30)
159
ax.scatter(treated['age'], treated['salary'], alpha=0.5, label='Treated', s=30, color='red')
160
ax.set_xlabel('Age')
161
ax.set_ylabel('Salary')
162
ax.set_title('Salary vs Age by Treatment')
163
ax.legend()
164
ax.grid(True, alpha=0.3)
165
166
# Propensity Score Distribution
167
ax = axes[1, 0]
168
ax.hist(df[df['treatment'] == 0]['propensity_score'], bins=20, alpha=0.6, label='Control', color='blue')
169
ax.hist(df[df['treatment'] == 1]['propensity_score'], bins=20, alpha=0.6, label='Treated', color='red')
170
ax.set_xlabel('Propensity Score')
171
ax.set_ylabel('Frequency')
172
ax.set_title('Propensity Score Distribution')
173
ax.legend()
174
ax.grid(True, alpha=0.3, axis='y')
175
176
# Treatment Effect Comparison
177
ax = axes[1, 1]
178
methods = ['Naive', 'Regression', 'PSM', 'Stratified']
179
effects = [naive_effect, regression_effect, psm_effect, stratified_effect]
180
true_effect = 5000
181
182
ax.bar(methods, effects, color=['red', 'orange', 'yellow', 'lightgreen'], alpha=0.7, edgecolor='black')
183
ax.axhline(y=true_effect, color='green', linestyle='--', linewidth=2, label=f'True Effect (${true_effect:.0f})')
184
ax.set_ylabel('Treatment Effect ($)')
185
ax.set_title('Treatment Effect Estimates by Method')
186
ax.legend()
187
ax.grid(True, alpha=0.3, axis='y')
188
189
for i, effect in enumerate(effects):
190
ax.text(i, effect + 200, f'${effect:.0f}', ha='center', va='bottom')
191
192
plt.tight_layout()
193
plt.show()
194
195
# 6. Doubly Robust Estimation
196
from sklearn.ensemble import RandomForestRegressor
197
198
# Propensity score model
199
ps_model_dr = LogisticRegression().fit(df[['age']], df['treatment'])
200
ps_scores = ps_model_dr.predict_proba(df[['age']])[:, 1]
201
202
# Outcome model
203
outcome_model = RandomForestRegressor(n_estimators=50, random_state=42)
204
outcome_model.fit(df[['treatment', 'age']], df['salary'])
205
206
# Doubly robust estimator
207
treated_mask = df['treatment'] == 1
208
control_mask = df['treatment'] == 0
209
210
# Adjust for propensity score
211
treated_adjusted = (treated_mask.astype(int) * df['salary']) / (ps_scores + 0.01)
212
control_adjusted = (control_mask.astype(int) * df['salary']) / (1 - ps_scores + 0.01)
213
214
# Outcome predictions
215
pred_treated = outcome_model.predict(df[['treatment', 'age']].replace({'treatment': 0, 1: 1}))
216
pred_control = outcome_model.predict(df[['treatment', 'age']].replace({'treatment': 1, 0: 0}))
217
218
dr_effect = treated_adjusted.sum() / treated_mask.sum() - control_adjusted.sum() / control_mask.sum()
219
print(f"\n6. Doubly Robust Estimation: ${dr_effect:.0f}")
220
221
# 7. Heterogeneous Treatment Effects
222
print(f"\n7. Heterogeneous Treatment Effects (by Age Quartile):")
223
224
for age_q in pd.qcut(df['age'], q=4, duplicates='drop').unique():
225
mask = (df['age'] >= age_q.left) & (df['age'] < age_q.right)
226
stratum_data = df[mask]
227
228
if (stratum_data['treatment'] == 0).sum() > 0 and (stratum_data['treatment'] == 1).sum() > 0:
229
treated_mean = stratum_data[stratum_data['treatment'] == 1]['salary'].mean()
230
control_mean = stratum_data[stratum_data['treatment'] == 0]['salary'].mean()
231
effect = treated_mean - control_mean
232
233
print(f" Age {age_q.left:.0f}-{age_q.right:.0f}: ${effect:.0f}")
234
235
# 8. Sensitivity Analysis
236
print(f"\n8. Sensitivity Analysis (Hidden Confounder Impact):")
237
238
# Vary hidden confounder correlation with outcome
239
for hidden_effect in [1000, 2000, 5000, 10000]:
240
adjusted_effect = regression_effect - hidden_effect * 0.1
241
print(f" If hidden confounder worth ${hidden_effect}: Effect = ${adjusted_effect:.0f}")
242
243
# 9. Summary Table
244
print(f"\n" + "="*60)
245
print("CAUSAL INFERENCE SUMMARY")
246
print("="*60)
247
print(f"True Treatment Effect: ${true_effect:,.0f}")
248
print(f"\nEstimates:")
249
print(f" Naive (BIASED): ${naive_effect:,.0f}")
250
print(f" Regression Adjustment: ${regression_effect:,.0f}")
251
print(f" Propensity Score Matching: ${psm_effect:,.0f}")
252
print(f" Stratification: ${stratified_effect:,.0f}")
253
print(f" Doubly Robust: ${dr_effect:,.0f}")
254
print("="*60)
255
256
# 10. Causal Graph (Text representation)
257
print(f"\n10. Causal Graph (DAG):")
258
print(f"""
259
Age → Treatment ← (Selection Bias)
260
↓ ↓
261
└─→ Salary
262
263
Interpretation:
264
- Age is a confounder
265
- Treatment causally affects Salary
266
- Age directly affects Salary
267
- Age affects probability of Treatment
268
""")
269
```
270
271
## Causal Assumptions
272
273
- **Unconfoundedness**: No unmeasured confounders
274
- **Overlap**: Common support on propensity scores
275
- **SUTVA**: No interference between units
276
- **Consistency**: Single version of treatment
277
278
## Treatment Effect Types
279
280
- **ATE**: Average Treatment Effect (overall)
281
- **ATT**: Average Treatment on Treated
282
- **CATE**: Conditional Average Treatment Effect
283
- **HTE**: Heterogeneous Treatment Effects
284
285
## Method Strengths
286
287
- **RCT**: Gold standard, controls all confounders
288
- **Matching**: Balances groups, preserves overlap
289
- **Regression**: Adjusts for covariates
290
- **Instrumental Variables**: Handles endogeneity
291
- **Causal Forests**: Learns heterogeneous effects
292
293
## Deliverables
294
295
- Causal graph visualization
296
- Treatment effect estimates
297
- Sensitivity analysis
298
- Heterogeneous treatment effects
299
- Covariate balance assessment
300
- Propensity score diagnostics
301
- Final causal inference report
302

© AJ Geddes · MIT · source · posted by @OpenSourceBuffGuy on promptparty.com

@OpenSourceBuffGuy

I find openly licensed prompts and post them here.

0 followers · 14,621 prompts

More by @OpenSourceBuffGuy

See all
Sea turtle carrying floating film studio island prompt image

Sea turtle carrying floating film studio island

Draws a giant sea turtle carrying a floating island film studio through a starry sky, where fairies polish rough film strips into golden film.

image-prompt, nano-banana, 3d-render, cartoon, fantasy-world, creatures, animals, whimsical, dreamy, cinematic, dramatic-lighting, vibrant-colors, bokeh, miniature, widescreen, night-scene, illustration, concept-art, surreal, storytelling, clay-3d

Desert buggy escapes drones past industrial outpost prompt image

Desert buggy escapes drones past industrial outpost

Builds a 15-second desert chase video where a racer in an armored buggy escapes drones past an industrial outpost, using five reference images with set jobs.

video-prompt, hailuo, action, multi-shot, timed-beats, camera-movement, reference-image, character-consistency, negative-prompt, cinematic, sci-fi, cars, landscape, aerial-view, tracking-shot, photorealistic, sound-effects, structured-output, long-form, widescreen

1 view
Cozy Pixel Art Farm Island Village prompt image

Cozy Pixel Art Farm Island Village

Draws a cozy 16-bit pixel-art farming village across six small islands joined by bridges, with exact counts for buildings, animals and crops.

image-prompt, gpt-image, pixel-art, isometric, game-assets, concept-art, maps, worldbuilding, cozy, vibrant-colors, ocean, landscape, wide-shot, widescreen, game-development, video-games, structured-output, whimsical, summer, high-angle, aerial-view, animals, negative-prompt, cityscape

1 view

Reviews

Loading reviews…

Discussion

Loading comments…