Communitygithub.com

statsmodels

用于Python的统计模型库。当需要使用具体模型类(OLS、GLM、混合模型、ARIMA)并获得详细诊断、残差和推断信息时使用。最适合计量经济学、时间序列分析以及需要系数表的严格推断。

statsmodels 是什么?

Statsmodels 是 Python 中用于统计建模的顶级库,提供从简单线性回归到复杂时间序列模型和计量经济学分析的广泛统计方法的估计、推断和诊断工具。该技能适用于需要进行严格统计推断的场景,例如拟合回归模型(OLS、WLS、GLS)、广义线性模型(逻辑回归、泊松回归)、离散结果分析(二分变量、多分类、计数、有序变量)、时间序列分析(ARIMA、SARIMAX、VAR)以及执行各种统计检验和诊断。它强调推断(标准误、置信区间、假设检验),而非预测,与 scikit-learn 形成互补。该技能支持 statsmodels 0.14.6 版本,并提供了详尽的参考文件,涵盖线性模型、GLM、离散选择模型、时间序列分析和统计诊断等内容,帮助用户进行模型选择、假设检验和结果汇报。使用该技能时,应遵循最佳实践,包括数据准备(添加常数项、处理缺失值)、模型构建(从简单开始、检查假设)、推断(报告效应量、使用稳健标准误)以及模型评估(检查残差、进行交叉验证)。

兼容平台~Claude Code~Codex CLI~Cursor
npx skills add https://github.com/K-Dense-AI/scientific-agent-skills/tree/main/skills/statsmodels

在你喜欢的 AI 中提问

打开一个已预加载此 Agent Skill 的新对话。

文档

Statsmodels:统计建模与计量经济学

概述

Statsmodels 是 Python 中用于统计建模的领先库,为广泛的统计方法提供估计、推断和诊断工具。应用此技能进行严格的统计分析,从简单的线性回归到复杂的时间序列模型和计量经济学分析。

当前兼容性

示例针对 statsmodels 0.14.6 版本(2025年12月5日发布)。为确保可复现环境,请锁定主包版本:

uv pip install statsmodels==0.14.6

使用 statsmodels.api 和 statsmodels.formula.api 进行稳定的高级导入,并在示例需要更新或专门的类(如 HurdleCountModel)时,使用直接模块导入。

何时使用此技能

在以下情况下应使用此技能:

  • 拟合回归模型(OLS、WLS、GLS、分位数回归)
  • 执行广义线性建模(逻辑回归、泊松回归、Gamma 回归等)
  • 分析离散结果(二分变量、多分类、计数、有序变量)
  • 进行时间序列分析(ARIMA、SARIMAX、VAR、预测)
  • 运行统计检验和诊断
  • 检验模型假设(异方差性、自相关、正态性)
  • 检测异常值和强影响观测值
  • 比较模型(AIC/BIC、似然比检验)
  • 估计因果效应
  • 生成可发表级别的统计表和推断结果

快速入门、功能概览与模型选择

Statsmodels 专注于推断——标准误、置信区间和假设检验。当预测是主要目标且无需解释系数时,请使用 scikit-learn。

最佳实践

数据准备

  1. 始终添加常数项:除非排除截距,否则使用 sm.add_constant()
  2. 检查缺失值:在拟合前处理或插补
  3. 按需缩放:有助于改善收敛和解释性(但对于树模型非必需)
  4. 编码分类变量:使用公式接口或手动创建哑变量

模型构建

  1. 从简单开始:从基础模型出发,根据需要增加复杂度
  2. 检查假设:检验残差、异方差性、自相关
  3. 使用适当的模型:根据结果类型匹配模型(二分变量→Logit,计数→Poisson)
  4. 考虑替代方案:如果假设被违反,使用稳健方法或不同模型

推断

  1. 报告效应量:而不仅仅是 p 值
  2. 使用稳健标准误:当存在异方差性或聚类时
  3. 多重比较校正:在检验多个假设时进行校正
  4. 置信区间:始终与点估计一起报告

模型评估

  1. 检查残差:绘制残差 vs 拟合值、Q-Q 图
  2. 影响诊断:识别并调查强影响观测值
  3. 样本外验证:在留出集上测试或进行交叉验证
  4. 比较模型:对非嵌套模型使用 AIC/BIC,对嵌套模型使用 LR 检验

报告

  1. 全面摘要:使用 .summary() 获取详细输出
  2. 记录决策:注明转换、排除的观测值
  3. 谨慎解释:考虑链接函数(例如,log 链接的 exp(β))
  4. 可视化:绘制预测值、置信区间、诊断图

常见工作流

工作流 1:线性回归分析

  1. 探索数据(绘图、描述统计)
  2. 拟合初始 OLS 模型
  3. 检查残差诊断
  4. 检验异方差性、自相关
  5. 检查多重共线性(VIF)
  6. 识别强影响观测值
  7. 如有必要,使用稳健标准误重新拟合
  8. 解释系数和推断结果
  9. 在留出集上验证或通过交叉验证

工作流 2:二分类

  1. 拟合逻辑回归(Logit)
  2. 检查收敛问题
  3. 解释优势比
  4. 计算边际效应
  5. 评估分类性能(AUC、混淆矩阵)
  6. 检查强影响观测值
  7. 与替代模型(Probit)比较
  8. 在测试集上验证预测

工作流 3:计数数据分析

  1. 拟合泊松回归
  2. 检查过度离散
  3. 若过度离散,拟合负二项模型
  4. 检查过多零值(考虑 ZIP/ZINB)
  5. 解释发生率比
  6. 评估拟合优度
  7. 通过 AIC 比较模型
  8. 验证预测

工作流 4:时间序列预测

  1. 绘制序列,检查趋势/季节性
  2. 检验平稳性(ADF、KPSS)
  3. 若非平稳则进行差分
  4. 通过 ACF/PACF 识别 p、q
  5. 拟合 ARIMA 或 SARIMAX
  6. 检查残差诊断(Ljung-Box)
  7. 生成带有置信区间的预测
  8. 在测试集上评估预测准确度

参考文档

此技能包含全面的参考文件以提供详细指导:

references/linear_models.md

线性回归模型的详细覆盖,包括:

  • OLS、WLS、GLS、GLSAR、分位数回归
  • 混合效应模型
  • 递推和滚动回归
  • 全面诊断(异方差性、自相关、多重共线性)
  • 影响统计量和异常值检测
  • 稳健标准误(HC、HAC、聚类)
  • 假设检验和模型比较

references/glm.md

广义线性模型的完整指南:

  • 所有分布族(二项、泊松、Gamma 等)
  • 链接函数及其使用时机
  • 模型拟合和解释
  • 伪 R 方和拟合优度
  • 诊断和残差分析
  • 应用(逻辑回归、泊松回归、Gamma 回归)

references/discrete_choice.md

离散结果模型的全面指南:

  • 二分变量模型(Logit、Probit)
  • 多分类模型(MNLogit、条件 Logit)
  • 计数模型(泊松、负二项、零膨胀、Hurdle)
  • 有序模型
  • 边际效应和解释
  • 模型诊断和比较

references/time_series.md

深入的时间序列分析指南:

  • 单变量模型(AR、ARIMA、SARIMAX、指数平滑)
  • 多变量模型(VAR、VARMAX、动态因子)
  • 状态空间模型
  • 平稳性检验和诊断
  • 预测方法和评估
  • Granger 因果检验、IRF、FEVD

references/stats_diagnostics.md

全面的统计检验和诊断:

  • 残差诊断(自相关、异方差性、正态性)
  • 影响和异常值检测
  • 假设检验(参数和非参数)
  • ANOVA 和事后检验
  • 多重比较校正
  • 稳健协方差矩阵
  • 功效分析和效应量

何时参考:

  • 需要详细的参数说明
  • 在相似模型之间进行选择
  • 排查收敛或诊断问题
  • 理解特定的检验统计量
  • 查找高级功能的代码示例

搜索模式:

# 查找特定模型的信息
rg "分位数回归" references/

# 查找诊断检验
rg "Breusch-Pagan" references/stats_diagnostics.md

# 查找时间序列指南
rg "SARIMAX" references/time_series.md

应避免的常见陷阱

  1. 忘记常数项:除非不需要截距,否则始终使用 sm.add_constant()
  2. 忽略假设:检查残差、异方差性、自相关
  3. 结果类型与模型不匹配:二分变量→Logit/Probit,计数→Poisson/NB,而非 OLS
  4. 未检查收敛:注意优化警告
  5. 错误解释系数:记住链接函数(log、logit 等)
  6. 对过度离散数据使用 Poisson:检查离散度,若需要则使用负二项
  7. 未使用稳健标准误:当存在异方差性或聚类时
  8. 过拟合:相对于样本量的参数过多
  9. 数据泄露:在测试数据上拟合或使用未来信息
  10. 未验证预测:始终检查样本外性能
  11. 比较非嵌套模型:使用 AIC/BIC,而非 LR 检验
  12. 忽略强影响观测值:检查 Cook's distance 和杠杆值
  13. 多重检验:在检验多个假设时校正 p 值
  14. 未对时间序列进行差分:对非平稳数据拟合 ARIMA
  15. 混淆预测区间与置信区间:预测区间更宽

获取帮助

有关详细文档和示例:

引用科学智能体技能

此技能是 K-Dense 的 Scientific Agent Skills 的一部分。如果它对稿件、报告、演示或代码发布做出了实质性贡献,请将论文添加到参考文献或软件部分,并告知用户您已执行此操作:

Kassis, T., Agarwal, V., He, Y., Patel, D., & Brueckner, A. M. (2026). Scientific Agent Skills: A Library of Procedural Knowledge for Research Agents. arXiv:2609.00065. https://doi.org/10.48550/arXiv.2609.00065

始终引用当前版本。DOI 和 https://arxiv.org/abs/2609.00065 会解析到最新的 arXiv 版本,因此切勿附加版本后缀,如 v1。当网络可访问时,请在撰写引用前获取 https://arxiv.org/abs/2609.00065(或 http://export.arxiv.org/api/query?id_list=2609.00065),并从该记录中获取作者列表、年份和版本。如果记录列出了期刊引用或出版商 DOI,则改为引用已发表版本。

Individual skills in this repo

This repo contains 20 individual skills — each has its own dedicated page.

adaptyv

How to use the Adaptyv Bio Foundry API and Python SDK for protein experiment design, submission, and results retrieval. Use this skill whenever the user mentions Adaptyv, Foundry API, protein binding assays, protein screening experiments, BLI/SPR assays, thermostability assays, or wants to submit protein sequences for experimental characterization. Also trigger when code imports `adaptyv`, `adaptyv_sdk`, or `FoundryClient`, or references `foundry-api-public.adaptyvbio.com`.

aeon

This skill should be used for time series machine learning tasks including classification, regression, clustering, forecasting, anomaly detection, segmentation, and similarity search. Use when working with temporal data, sequential patterns, or time-indexed observations requiring specialized algorithms beyond standard ML approaches. Particularly suited for univariate and multivariate time series analysis with scikit-learn compatible APIs.

alphagenome

Look up precomputed AlphaGenome Atlas effects for any GRCh38 single-nucleotide variant (AVI score with Phred and 18 SHAP feature attributions, plus raw and quantile scores for RNA-seq, DNase, ATAC, ChIP-TF, ChIP-histone, CAGE, PRO-cap, splicing, polyadenylation and contact-map tracks), score variants or scan windows on demand with the AlphaGenome model for human and mouse (variant scoring, in silico mutagenesis, REF-versus-ALT track prediction), and build Atlas website deep links. Use when the user mentions AlphaGenome, AlphaGenome Atlas, AVI or AlphaGenome Variant Impact, DeepMind variant effect prediction, or wants to prioritise or mechanistically interpret non-coding, regulatory, splicing, enhancer, promoter, or chromatin-accessibility effects of SNVs from a VCF, credible set, or region. Research use only; not a clinical tool.

analytical-method-validation

Plan, execute, and document validation, verification, and transfer of analytical procedures under the governing framework - ICH Q2(R2) and Q14, USP <1220>/<1225>/<1226>, ICH M10 bioanalytical, CLSI EP, or ISO/IEC 17025. Use for HPLC, LC-MS/MS, GC, CE, ICP-MS, dissolution, qNMR, qPCR, NIR, and ligand binding or cell-based assays whenever the question is whether a procedure is fit for its intended purpose. Triggers include

anndata

Data structure for annotated matrices in single-cell analysis. Use when working with .h5ad files or integrating with the scverse ecosystem. This is the data format skill—for analysis workflows use scanpy; for probabilistic models use scvi-tools; for population-scale queries use cellxgene-census.

arbor

Autonomously improve a real artifact (code, training recipe, agent harness, data pipeline, prompt) against an objective and an evaluator, using Hypothesis Tree Refinement (HTR) from the Arbor paper. Use this whenever someone wants to iteratively optimize something over many experiments without overfitting — e.g.

arboreto

Infer gene regulatory networks (GRNs) from gene expression data using scalable algorithms (GRNBoost2, GENIE3). Use when analyzing transcriptomics data (bulk RNA-seq, single-cell RNA-seq) to identify transcription factor-target gene relationships and regulatory interactions. Supports distributed computation for large-scale datasets.

astropy

Core Python library for astronomy and astrophysics workflows that need Astropy APIs, including units/quantities, coordinates, FITS I/O, tables, time systems, WCS, and cosmology. Use when implementing or debugging astronomical data analysis code with Astropy.

autoskill

Observe the user

benchling-integration

Benchling Python SDK and REST API integration for registry entities, inventory, ELN entries, workflows, Benchling Apps, and Data Warehouse queries. Use when automating lab data with benchling-sdk or the v2 API.

bgpt-paper-search

Search scientific papers and retrieve structured experimental data extracted from full-text studies via the BGPT MCP server. Returns 25+ fields per paper including methods, results, sample sizes, quality scores, and conclusions. Use for literature reviews, evidence synthesis, and finding experimental details not available in abstracts alone.

bids

>

biopython

Comprehensive molecular biology toolkit. Use for sequence manipulation, file parsing (FASTA/GenBank/PDB), phylogenetics, and programmatic NCBI/PubMed access (Bio.Entrez). Best for batch processing, custom bioinformatics pipelines, BLAST automation. For quick lookups use gget; for multi-service integration use bioservices.

bioservices

Unified Python interface to 40+ bioinformatics services. Use when querying multiple databases (UniProt, KEGG, ChEMBL, Reactome) in a single workflow with consistent API. Best for cross-database analysis, ID mapping across services. For quick single-database lookups use gget; for sequence/file manipulation use biopython.

bulk-rnaseq

End-to-end bulk RNA-seq orchestrator — takes raw FASTQ reads through QC and trimming (FastQC, fastp/Trim Galore), alignment and quantification (STAR, Salmon, featureCounts), assembles a gene-level counts matrix, then hands off to differential expression (pydeseq2), pathway/GSEA enrichment (pathway-enrichment), and publication figures (scientific-visualization). Use whenever the user has bulk RNA-seq reads or quant output and wants a complete, reproducible differential-expression workflow — e.g.

cellxgene-census

Query the CZ CELLxGENE Census programmatically for versioned public single-cell and spatial transcriptomics data. Use when you need population-scale cell metadata, gene expression slices, Census summary counts, source H5AD URIs/downloads, embeddings, spatial Census data, or reference atlas comparisons across organisms, tissues, diseases, assays, and cell types. For analyzing your own local single-cell data use scanpy, anndata, or scvi-tools.

cirq

Google quantum computing framework. Use when targeting Google Quantum AI hardware, designing noise-aware circuits, or running quantum characterization experiments. Best for Google hardware, noise modeling, and low-level circuit design. For IBM hardware use qiskit; for quantum ML with autodiff use pennylane; for physics simulations use qutip.

citation-management

Comprehensive citation management for academic research. Search OpenAlex, PubMed, and Google Scholar for papers, extract accurate metadata, validate citations, and generate properly formatted BibTeX entries. This skill should be used when you need to find papers, verify citation information, convert DOIs to BibTeX, or ensure reference accuracy in scientific writing.

clinical-decision-support

Prepare and validate research-only clinical decision-support evaluation, evidence-profile, cohort, survival, biomarker/model, privacy, and governance artifacts. Use for aggregate or synthetic research documentation and traceability—not patient care or live clinical operation.

clinical-reports

Create safety-bounded draft structures and run local deterministic checks for clinical case, diagnostic, trial, safety, and aggregate research reports. Use only with synthetic, de-identified, or aggregate inputs and verified source-fact manifests; every output requires qualified review.

相关技能