Communitygithub.com

統計分析

為研究資料提供引導式統計分析:包含檢定選擇、假設檢查、效果量、檢定力分析、貝氏替代方案及 APA 格式報告。

統計分析 是什麼?

此技能為研究資料的統計分析提供了一個完整的引導式工作流程,旨在讓分析結果經得起審查者的考驗。它涵蓋從假設檢定(如 t 檢定、ANOVA、卡方檢定)、迴歸、相關分析到貝氏統計方法的完整流程,並強制要求系統性地檢查假設、計算效果量與檢定力,最終產出 APA 格式的報告。該技能支援 Python 生態系,以 pingouin 作為主要統計套件,並整合 statsmodels 進行迴歸與診斷,以及 PyMC 與 ArviZ 進行貝氏建模。對於低階模型 API,建議參考 statsmodels 與 pymc 技能。其核心價值在於引導使用者遵循「先規劃、再檢查、後執行、最後報告」的嚴謹分析順序,避免常見的統計謬誤,如資料窺探或僅報告顯著結果。

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

在你喜歡的 AI 中提問

開啟一個已預先載入此 Agent Skill 的新對話。

說明文件

統計分析 是做什麼的?

概述

執行假設檢定(t 檢定、ANOVA、卡方檢定)、迴歸、相關分析與貝氏分析,並進行系統性的假設檢查、效果量計算與 APA 風格報告。目標是產出一份審查者無法挑剔的分析:正確的檢定、經驗證的假設、誠實的效果量以及完整的報告。

何時使用此技能

在以下情況使用此技能:

  • 進行統計假設檢定(t 檢定、ANOVA、卡方檢定、無母數檢定)
  • 執行迴歸或相關分析
  • 執行貝氏統計分析
  • 檢查統計假設與診斷
  • 計算效果量與進行檢定力分析
  • 以 APA 格式報告統計結果
  • 分析研究用的實驗或觀察資料

安裝

使用 uv 安裝此技能所需的函式庫。在正式環境中應鎖定版本;探索用時可以不鎖定版本。

# 核心頻率論者套件(Python 3.10+;建議使用 3.12+ 以獲得最新 SciPy/ArviZ)
uv pip install "pingouin>=0.6" "scipy>=1.11" "statsmodels>=0.14.6" pandas matplotlib seaborn

# 貝氏建模(PyMC 5 + ArviZ)
uv pip install "pymc>=5.0" "arviz>=1.0"

相容性說明(已針對 pingouin 0.6.1、statsmodels 0.14.6、arviz 1.2 驗證,2026 年):

  • Pingouin 0.6.0 重新命名了輸出欄位以移除特殊字元:p_val、cohen_d、CI95、p_unc(先前在 0.5.x 中為 p-val、cohen-d、CI95%、p-unc)。以下範例使用當前名稱;若仍使用 0.5.x 版本,請使用連字號形式。
  • statsmodels + SciPy:使用 statsmodels>=0.14.6 搭配 scipy>=1.11,以避免在 SciPy 1.16+ 上發生 _lazywhere 匯入錯誤。
  • ArviZ 1.x:az.summary() 現在預設使用 89% 區間(eti89 欄位),且寬度參數為 ci_prob(而非 hdi_prob)。若要報告傳統的 95% 可信區間,請傳入 az.summary(trace, ci_prob=0.95)。
  • Pingouin 已移除單側貝氏因子:pg.ttest(..., alternative='greater') 會靜默地捨棄 BF10 欄位,且 pg.bayesfactor_ttest 在單側替代方案時會引發錯誤。對於單側貝氏檢定,請直接使用 PyMC(計算方向性假設的後驗機率)或 JASP/R 的 BayesFactor。

如需模型專用 API(OLS、GLM、ARIMA),請參考 statsmodels 技能。如需 PyMC 工作流程,請參考 pymc 技能。


分析工作流程

每一個穩健的分析都遵循相同的流程。跳過步驟是分析被撤稿的原因,因此請依序執行每個步驟,並說明每一步做了什麼。

  1. 在接觸資料前先確定問題。 陳述假設、結果變數與預測變數、以及研究設計(獨立 vs. 配對、組數)。現在就承諾一個計劃中的檢定——在偷看結果後才選擇檢定是一種 p-hacking,即使是在無意中發生。
  2. 檢查資料。 按組別:樣本數、平均數、標準差、中位數、遺漏值。在任何檢定之前先繪製原始資料的圖形(直方圖或盒狀圖)。不均衡的組別大小、遺漏值、天花板/地板效應和離群值,都會改變適用哪種檢定——應將它們呈現給使用者,而不是默默地繞過它們。
  3. 選擇檢定,使用下方的快速參考表,或對於超出基本範圍的設計(計數、時間至事件、信度、因子設計),參考 references/test_selection_guide.md。
  4. 檢查假設,使用 scripts/assumption_checks.py。如果某個假設被違反,請切換至補救檢定(見下表),並同時報告原計劃與變更。
  5. 執行檢定,並務必同時計算效果量——p 值告訴你效果存在;效果量則告訴你這效果是否值得關心。
  6. 使用下方的 APA 範本進行報告,包括描述性統計、精確統計量、含信賴區間的效果量,以及所執行的假設檢查。

如果使用者只需要某個步驟(例如:「我需要多少參與者?」),可以直接跳到該章節——但仍需確認該計算所依據的設計假設。


檢定選擇指南

快速參考:選擇正確的檢定

如需更全面的指導(計數、存活、信度、因子設計),請使用 references/test_selection_guide.md。快速參考:

比較兩組:

  • 獨立、連續、常態分佈 → 獨立樣本 t 檢定
  • 獨立、連續、非常態分佈 → Mann-Whitney U 檢定
  • 配對、連續、常態分佈 → 成對樣本 t 檢定
  • 配對、連續、非常態分佈 → Wilcoxon 符號秩檢定
  • 二元結果 → 卡方檢定或 Fisher 精確檢定

比較 3 組以上:

  • 獨立、連續、常態分佈 → 單因子變異數分析
  • 獨立、連續、非常態分佈 → Kruskal-Wallis 檢定
  • 配對、連續、常態分佈 → 重複測量變異數分析
  • 配對、連續、非常態分佈 → Friedman 檢定

關係:

  • 兩個連續變數 → Pearson 相關(常態)或 Spearman 相關(非常態)
  • 連續結果變數搭配一個或多個預測變數 → 線性迴歸
  • 二元結果變數搭配一個或多個預測變數 → 邏輯斯迴歸

貝氏替代方案: 所有檢定都有貝氏版本,可提供關於假設的直接機率陳述、量化證據的貝氏因子,以及支持虛無假設的能力。請參閱 references/bayesian_statistics.md。


假設檢查

在解釋檢定結果之前,務必檢查假設,並報告這些檢查——審查者會找這個。

使用隨附的 scripts/assumption_checks.py 模組。從技能目錄(skills/statistical-analysis/)執行 Python,或將 scripts/ 加入 sys.path:

from assumption_checks import comprehensive_assumption_check

# 離群值 + 常態性(按組別)+ 變異數同質性,含圖形
results = comprehensive_assumption_check(
    data=df,
    value_col='score',
    group_col='group',  # 可選:用於組間比較
    alpha=0.05
)

如需針對性檢查,請匯入個別函數:

from assumption_checks import (
    check_normality,                # Shapiro-Wilk + Q-Q 圖 + 直方圖
    check_normality_per_group,
    check_homogeneity_of_variance,  # Levene 檢定 + 盒狀圖
    check_linearity,                # 簡單迴歸的散佈圖 + 殘差圖
    check_regression_diagnostics,   # 完整的 OLS 診斷(見下方迴歸章節)
    detect_outliers                 # IQR 或 z-score 方法
)

result = check_normality(data=df['score'], name='Test Score', alpha=0.05, plot=True)
print(result['interpretation'])
print(result['recommendation'])

當假設被違反時該怎麼做

常態性被違反:

  • 輕微違反 + 每組 n > 30 → 繼續使用參數檢定(穩健)
  • 中度違反 → 使用無母數替代方案
  • 嚴重違反 → 轉換資料或使用無母數檢定

變異數同質性被違反:

  • 對於 t 檢定 → 使用 Welch t 檢定(pg.ttest 在 correction='auto' 時會自動套用)
  • 對於 ANOVA → 使用 Welch ANOVA (pg.welch_anova) 或 Brown-Forsythe
  • 對於迴歸 → 使用穩健標準誤或加權最小平方法

線性被違反(迴歸):

  • 加入多項式項、轉換變數,或使用非線性模型 / GAM

當樣本數增加時,正式檢定會變得過度敏感:對於 n ≥ 100,應更重視 Q-Q 圖而非 Shapiro-Wilk 的 p 值。如需全面指導,請參閱 references/assumptions_and_diagnostics.md。


執行統計檢定

主要函式庫:

  • pingouin:使用者友善的檢定,預設會回傳效果量——標準檢定建議優先使用
  • scipy.stats:核心統計檢定
  • statsmodels:迴歸、診斷、檢定力分析
  • pymc + arviz:貝氏建模與診斷

含完整報告的 T 檢定

import pingouin as pg

# correction='auto' 會在變異數不相等時套用 Welch 校正
result = pg.ttest(group_a, group_b, correction='auto')

# Pingouin >= 0.6 的欄位名稱
t_stat = result['T'].values[0]
df = result['dof'].values[0]
p_value = result['p_val'].values[0]
cohens_d = result['cohen_d'].values[0]
ci_lower, ci_upper = result['CI95'].values[0]  # 平均差異的信賴區間

print(f"t({df:.0f}) = {t_stat:.2f}, p = {p_value:.3f}, d = {cohens_d:.2f}")

含事後檢定的 ANOVA

import pingouin as pg

aov = pg.anova(dv='score', between='group', data=df, detailed=True)
print(aov)

# 效果量:偏 eta 平方
eta_p2 = aov['np2'].values[0]

# 如果顯著,進行事後檢定(Tukey HSD 控制家庭 wise 錯誤率)
if aov['p_unc'].values[0] < 0.05:
    posthoc = pg.pairwise_tukey(dv='score', between='group', data=df)
    print(posthoc)  # 每組對包含 Hedges' g

含診斷的線性迴歸

import statsmodels.api as sm
from assumption_checks import check_regression_diagnostics

X = sm.add_constant(X_predictors)  # 加入截距
model = sm.OLS(y, X).fit()
print(model.summary())

# 4 面板殘差圖 + Shapiro-Wilk、Breusch-Pagan、Durbin-Watson、VIF
diag = check_regression_diagnostics(model)
print(diag['interpretation'])
print(diag['vif'])

# 如果標記了異質變異數,改為報告穩健標準誤
robust = model.get_robustcov_results('HC3')

貝氏 T 檢定

import pymc as pm
import arviz as az
import numpy as np

with pm.Model() as model:
    # 先驗
    mu1 = pm.Normal('mu_group1', mu=0, sigma=10)
    mu2 = pm.Normal('mu_group2', mu=0, sigma=10)
    sigma = pm.HalfNormal('sigma', sigma=10)

    # 概似
    y1 = pm.Normal('y1', mu=mu1, sigma=sigma, observed=group_a)
    y2 = pm.Normal('y2', mu=mu2, sigma=sigma, observed=group_b)

    # 衍生量
    diff = pm.Deterministic('difference', mu1 - mu2)

    trace = pm.sample(2000, tune=1000)

# ArviZ 1.x 預設為 89% 區間;為報告明確請求 95%
print(az.summary(trace, var_names=['difference'], ci_prob=0.95))

# 直接機率陳述(這就是單側問題的答案)
prob_greater = np.mean(trace.posterior['difference'].values > 0)
print(f"P(mu1 > mu2 | data) = {prob_greater:.3f}")

# ArviZ 1.x 移除了 az.plot_posterior;請使用 plot_dist(在 0.x 上,plot_posterior 仍然可用)
az.plot_dist(trace, var_names=['difference'], ci_prob=0.95)

調整先驗以符合資料規模(例如,sigma=10 適用於標準差接近 10 的結果;以觀察到的標準差作為指導),並在報告中陳述先驗。


效果量

**效果量量化幅度;p 值僅指示存在與否。**對每個檢定都應報告效果量。完整指南請參閱 references/effect_sizes_and_power.md。

快速參考:常見效果量

檢定效果量小中大
T 檢定Cohen's d0.200.500.80
ANOVAη²_p0.010.060.14
相關r0.100.300.50
迴歸R²0.020.130.26
卡方檢定Cramér's V0.070.210.35

基準是慣例,而非鐵律——「小」效果可能至關重要(藥物副作用),而「大」效果可能微不足道。請根據情境解讀。

計算效果量

Pingouin 會在其檢定中回傳效果量(pg.ttest 的 cohen_d、pg.anova 的 np2、pg.pairwise_tukey 的 hedges;pg.corr 的 r 本身就是效果量)。

效果量的信賴區間

報告效果量的信賴區間以顯示其精確度。使用 pg.compute_esci(注意:pg.compute_effsize_from_t 只回傳點估計——它不回傳信賴區間):

import pingouin as pg

d = pg.compute_effsize(group_a, group_b, eftype='cohen')
ci_lower, ci_upper = pg.compute_esci(stat=d, nx=len(group_a), ny=len(group_b),
                                     eftype='cohen', confidence=0.95)
print(f"d = {d:.2f}, 95% CI [{ci_lower:.2f}, {ci_upper:.2f}]")

檢定力分析

事前檢定力分析(研究規劃)

在收集資料前確定所需的樣本數:

from statsmodels.stats.power import tt_ind_solve_power, FTestAnovaPower

# T 檢定:要檢測 d = 0.5,每組需要多少樣本數?
n_required = tt_ind_solve_power(
    effect_size=0.5,
    alpha=0.05,
    power=0.80,
    ratio=1.0,
    alternative='two-sided'
)
print(f"每組所需樣本數:{n_required:.0f}")

# 單因子 ANOVA:要檢測 Cohen's f = 0.25,需要多少樣本數?
# 注意:參數是 k_groups;effect_size 是 Cohen's f(f = sqrt(eta2/(1-eta2)));
# 且 solve_power 回傳的是總樣本數,而非每組樣本數。
import math
anova_power = FTestAnovaPower()
n_total = anova_power.solve_power(
    effect_size=0.25,
    k_groups=3,
    alpha=0.05,
    power=0.80
)
print(f"所需總樣本數:{math.ceil(n_total)}(每組 {math.ceil(n_total / 3)} 人)")

敏感度分析(事後分析)

確定該研究能夠檢測到的效果量:

# 每組 n=50,在 80% 檢定力下,我們能檢測到多大的效果量?
detectable_d = tt_ind_solve_power(
    effect_size=None,  # 解這個
    nobs1=50,
    alpha=0.05,
    power=0.80,
    ratio=1.0,
    alternative='two-sided'
)
print(f"研究能檢測到 d >= {detectable_d:.2f}")

注意:事後「觀察檢定力」(根據觀察到的效果計算檢定力)是循環論證且具誤導性的——它是 p 值的確定性函數。如果研究已完成,而有人詢問檢定力,請改為執行敏感度分析。

詳細指導請參閱 references/effect_sizes_and_power.md。


報告結果

遵循 references/reporting_standards.md 的 APA 風格。每份報告都需要:

  1. 描述性統計:所有組別/變數的平均數、標準差、樣本數
  2. 檢定統計量:檢定名稱、統計量、自由度、精確 p 值(p = .034,而非 p < .05;僅在 p < .001 時使用 p < .001)
  3. 效果量:含信賴區間
  4. 假設檢查:執行了哪些檢定、結果以及採取的因應措施
  5. 所有計劃中的分析:包括不顯著的發現——省略它們就是摘櫻桃

報告範本範例

獨立樣本 T 檢定

A 組(n = 48, M = 75.2, SD = 8.5)的分數顯著高於
B 組(n = 52, M = 68.3, SD = 9.2), t(98) = 3.45, p < .001, d = 0.79, 95% CI [0.37, 1.20]。

假設檢查:各組的常態性(Shapiro-Wilk, p > .05)與變異數同質性(Levene 檢定, p = .38)均未受違反。

單因子 ANOVA

一因子變異數分析顯示組別對分數有顯著效果,F(2, 87) = 5.62, p = .005, η²_p = .11, 90% CI [.02, .22]。
Tukey HSD 事後檢定顯示,A 組(n = 30, M = 72.1, SD = 8.3)的分數顯著高於 C 組(n = 29, M = 64.5, SD = 9.1),p = .008, Hedges' g = 0.87。A 組與 B 組之間(n = 31, M = 68.9, SD = 7.8),以及 B 組與 C 組之間均無顯著差異(p > .05)。

線性迴歸

迴歸模型顯著,F(2, 97) = 14.23, p < .001, R² = .23, 調整後 R² = .21。
預測變數 X1(β = .34, p < .001)和 X2(β = .21, p = .012)均為分數的顯著預測因子。
診斷檢查:常態性(Shapiro-Wilk, p = .23)、變異數同質性(Breusch-Pagan, p = .41)、無多重共線性(所有 VIF < 2)以及殘差獨立性(Durbin-Watson = 1.89)均符合假設。

相關技能與參考資料

此技能整合了來自多個專有技能的內容,以提供統一的統計分析工作流程:

  • statsmodels:用於迴歸、診斷與檢定力分析的專用 API
  • pymc:用於自訂貝氏分析的專用 API
  • references/ 目錄包含詳細的指南與參考資料

對於需要更專業 API(如低階模型)的使用案例,請直接查閱這些技能。


參考資料

  • references/test_selection_guide.md:全面的檢定選擇指南,包括計數、存活、信度與因子設計
  • references/effect_sizes_and_power.md:效果量與檢定力分析的詳細指導
  • references/assumptions_and_diagnostics.md:假設檢查與診斷的全面指導
  • references/bayesian_statistics.md:貝氏方法的詳細指導
  • references/reporting_standards.md:APA 報告標準

對於僅需快速確認的使用者,上方提供的快速參考與程式碼範例應足以應付大多數常見情況。

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.

相關技能