Statsmodels statistical modeling

From findscripter/everything-skills · View interactive version

Statsmodels statistical modeling is an AI agent skill from the GitHub repository findscripter/everything-skills. 当用 Python 做严谨统计建模与推断(线性/广义线性回归、离散选择、时间序列预测、假设检验与诊断)时使用;用 statsmodels 拟合模型并产出含系数/置信区间/p 值的可发表结果与残差诊断;不适用于纯预测机器学习(用 scikit-learn)、深度学习/GPU 训练、仅做数据清洗或画图。触发词:statsmodels、OLS、回归、logistic、GLM、ARIMA、时间序列、假设检验、置信区间、p值

How to use this skill

Skill file

何时使用

适用场景:

不该用的边界:

步骤 / 指令

先按结果类型选模型(最常见的错是用错模型):

| 结果变量 | 模型 |

|---|---|

| 连续 | OLS(异方差→WLS 或稳健 SE) |

| 二元 0/1 | Logit / Probit |

| 计数 | GLM(family=Poisson);过离散→NegativeBinomial |

| 正偏态连续 | GLM(family=Gamma) |

| 多分类/有序 | MNLogit / OrderedModel |

| 时间序列 | ARIMA / SARIMAX / VAR |

通用流程:

  1. 探查数据:缺失值先处理;区分数值/类别列。
  2. 加常数项:X = sm.add_constant(X_data)——除非刻意去截距,否则必须加(用 formula API 自动含截距)。
  3. 拟合:model.fit(),注意优化是否收敛(看 warning)。
  4. 读结果:print(results.summary()),关注系数、p 值、置信区间、R²/伪 R²、AIC/BIC。
  5. 诊断:残差 vs 拟合值散点、Q-Q 图;按需做异方差/自相关/正态性检验。
  6. 稳健推断:有异方差或聚类时用稳健标准误(cov_type='HC3' 或 HAC/cluster)。
  7. 比较模型:嵌套用似然比检验(LR),非嵌套用 AIC/BIC(越小越好)。
  8. 预测:results.get_prediction(X_new).summary_frame(),含均值、置信区间与预测区间。

Formula API(R 风格,推荐用 DataFrame 时):smf.ols('y ~ x1 + x2 + x1:x2', data=df).fit();类别列 C(group);交互 x1*x2;多项式 I(x**2);对应有 smf.logit / smf.poisson。

安装:uv pip install statsmodels(可选 pandas numpy scipy matplotlib)。

示例

OLS 线性回归 + 异方差诊断:

import statsmodels.api as sm
from statsmodels.stats.diagnostic import het_breuschpagan

X = sm.add_constant(X_data)            # 务必加截距
results = sm.OLS(y, X).fit()
print(results.summary())               # 系数/p值/置信区间/R²
print(f"R-squared: {results.rsquared:.4f}")

# Breusch-Pagan 异方差检验;p<0.05 提示异方差
bp = het_breuschpagan(results.resid, X)
print(f"Breusch-Pagan p: {bp[1]:.4f}")
if bp[1] < 0.05:                       # 有异方差→改用稳健标准误
    results = sm.OLS(y, X).fit(cov_type="HC3")

Logistic 回归(二元结果)+ 优势比 + 边际效应:

from statsmodels.discrete.discrete_model import Logit
res = Logit(y_binary, sm.add_constant(X_data)).fit()
print(res.summary())
print("Odds ratios:\n", np.exp(res.params))   # log-odds→优势比
print(res.get_margeff().summary())            # 平均边际效应
probs = res.predict()                          # 预测概率

ARIMA 时间序列预测(先验平稳,再定阶):

from statsmodels.tsa.stattools import adfuller
from statsmodels.tsa.arima.model import ARIMA

if adfuller(y_series)[1] > 0.05:        # ADF p>0.05→非平稳,需差分
    pass                                 # 由 ARIMA 的 d 阶处理,或 .diff().dropna()
res = ARIMA(y_series, order=(1, 1, 1)).fit()
print(res.summary())
fc = res.get_forecast(steps=10).summary_frame()  # 含均值与置信区间
res.plot_diagnostics(figsize=(12, 8))            # 残差诊断(Ljung-Box 等)

Poisson GLM + 过离散检查(过离散则换负二项):

res = sm.GLM(y_counts, sm.add_constant(X_data),
             family=sm.families.Poisson()).fit()
od = res.pearson_chi2 / res.df_resid    # >1.5 视为过离散
if od > 1.5:
    from statsmodels.discrete.count_model import NegativeBinomial
    res = NegativeBinomial(y_counts, sm.add_constant(X_data)).fit()

模型比较:

# 非嵌套:比 AIC/BIC(越小越好)
# 嵌套:似然比检验
from scipy import stats
lr = 2 * (full.llf - reduced.llf)
p = 1 - stats.chi2.cdf(lr, full.df_model - reduced.df_model)

注意事项

互见


采编自 sickn33/antigravity-awesome-skills(MIT 许可);该技能内容原署 K-Dense Inc.,原始声明为 BSD-3-Clause,均可再分发。

Use this skill with your AI agent: Open on Skill Issue to copy, download, or add to your library. Works with Claude, ChatGPT, Gemini, Cursor, Windsurf and more.