技能创建器
skill-creator
创建、改进和评估自定义技能,把专业流程转化为可重复使用的 AI 能力。
ds-causal-inference【数据与研究】Implements causal models, directed acyclic graphs (DAGs), confounding adjustment, and mediation analysis for causal discovery
独立 GitHub 快照 · 自动分类 · 以原作者文档为准
name: ds-causal-inference compatibility: opencode completeness: 95 content-types:
Comprehensive guide to causal inference in machine learning and data science workflows.
Causal Inference is a critical component of the machine learning workflow. This skill covers:
import pandas as pd
import numpy as np
import statsmodels.api as sm
from sklearn.linear_model import LogisticRegression
from sklearn.model_selection import train_test_split
def estimate_ate_ols(df: pd.DataFrame, treatment_col: str, outcome_col: str, confounders: list) -> dict:
"""Estimate Average Treatment Effect using Ordinary Least Squares with confounders."""
if treatment_col not in df.columns or outcome_col not in df.columns:
raise ValueError("Treatment or outcome column missing")
X = df[confounders].values
X = sm.add_constant(X)
y = df[outcome_col].values
treatment = df[treatment_col].values
model = sm.OLS(y, X).fit()
coef_treatment = model.params[treatment_col] if treatment_col in model.params else 0.0
# Propensity score estimation for robustness check
ps_model = LogisticRegression()
ps_model.fit(X[:, 1:], treatment)
df['propensity'] = ps_model.predict_proba(X[:, 1:])[:, 1]
return {
'method': 'OLS with Confounders'
'ate': float(coef_treatment)
'confidence_interval': tuple(model.conf_int().loc[treatment_col])
'p_value': float(model.pvalues[treatment_col])
'r_squared': float(model.rsquared)
}
import logging
import pandas as pd
import numpy as np
from typing import Any, Dict, List
from sklearn.linear_model import LogisticRegression, LinearRegression
from sklearn.model_selection import cross_val_score
logger = logging.getLogger(__name__)
class CausalInference:
"""Production implementation of Causal Inference using IPW and Double Robust Estimation."""
def __init__(self, confounders: List[str], treatment_col: str, outcome_col: str):
self.confounders = confounders
self.treatment_col = treatment_col
self.outcome_col = outcome_col
self.propensity_model = LogisticRegression(max_iter=1000)
self.outcome_model = LinearRegression()
self.fitted = False
def _validate_data(self, data: pd.DataFrame) -> None:
missing = [c for c in self.confounders + [self.treatment_col, self.outcome_col] if c not in data.columns]
if missing:
raise ValueError(f"Missing columns: {missing}")
if data[self.treatment_col].nunique() != 2:
raise ValueError("Treatment variable must be binary")
def fit(self, data: pd.DataFrame) -> 'CausalInference':
self._validate_data(data)
X = data[self.confounders].values
T = data[self.treatment_col].values
Y = data[self.outcome_col].values
self.propensity_model.fit(X, T)
ps = self.propensity_model.predict_proba(X)[:, 1]
ipw_weights = T / ps + (1 - T) / (1 - ps)
self.outcome_model.fit(X, Y)
self.weights = ipw_weights
self.fitted = True
logger.info("Causal model fitted successfully with IPW weights.")
return self
def execute(self, data: pd.DataFrame) -> Dict[str, Any]:
if not self.fitted:
raise RuntimeError("Model must be fitted before execution")
self._validate_data(data)
X = data[self.confounders].values
T = data[self.treatment_col].values
Y = data[self.outcome_col].values
ps = self.propensity_model.predict_proba(X)[:, 1]
ipw_weights = T / ps + (1 - T) / (1 - ps)
predicted_treated = self.outcome_model.predict(X)
ate = np.mean(ipw_weights * (Y - predicted_treated))
return {
'status': 'success'
'average_treatment_effect': float(ate)
'standard_error': float(np.std(ipw_weights * (Y - predicted_treated)) / np.sqrt(len(Y)))
'sample_size': len(Y)
'confounders_used': self.confounders
}
| Pitfall | Problem | Solution | |
Authoritative documentation links for this skill's domain. The model follows markdown links at load time to resolve external references and inline content.