Communitygithub.com

統計分析

研究データのためのガイド付き統計分析:検定選択、仮定の確認、効果量、検出力分析、ベイズ代替手法、APA形式のレポート作成をカバーします。グループ比較、仮説検定、実験・調査データの分析、統計的仮定の確認、必要サンプルサイズの計算、結果の記述に使用します。

統計分析 とは?

このスキルは、研究者やデータ分析者向けに設計された包括的な統計分析アシスタントです。t検定、ANOVA、カイ二乗検定、相関分析、回帰分析、ノンパラメトリック検定、ベイズ統計など、幅広い仮説検定手法を体系的にサポートします。主な特徴として、検定前の仮定チェック(正規性、等分散性、線形性など)の自動化、効果量とその信頼区間の計算、APA形式に準拠した結果報告テンプレートの提供、検出力分析によるサンプルサイズ設計が含まれます。このスキルは、Pingouin、StatsModels、SciPy、PyMC、ArviZといったPythonの主要統計ライブラリを統合し、コード例とともに実践的な分析ワークフローを提示します。特に、仮定違反時の代替検定への切り替えや、ベイズ手法による直接的な確率解釈など、堅牢で再現可能な分析を目指すユーザーに役立ちます。

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

お気に入りのAIに質問する

このエージェントスキルを事前に読み込んだ状態で新しいチャットを開きます。

ドキュメント

統計分析 は何をしますか?

概要

仮説検定(t検定、ANOVA、カイ二乗検定)、回帰分析、相関分析、ベイズ分析を実施し、系統的な仮定チェック、効果量、APAスタイルのレポート作成を行います。目標は、査読者が批判できない分析、すなわち適切な検定、検証済みの仮定、正直な効果量、完全なレポートを作成することです。

このスキルを使うべきタイミング

以下の場合にこのスキルを使用してください:

  • 統計的仮説検定(t検定、ANOVA、カイ二乗検定、ノンパラメトリック検定)を実施する場合
  • 回帰分析または相関分析を実行する場合
  • ベイズ統計分析を実行する場合
  • 統計的仮定と診断をチェックする場合
  • 効果量を計算し、検出力分析を実施する場合
  • 統計結果をAPA形式で報告する場合
  • 実験データまたは観察データを研究目的で分析する場合

インストール

uv を使用して、このスキルで使用するライブラリをインストールします。本番環境ではバージョンを固定し、探索目的の場合は固定しなくても問題ありません。

# コアの頻度論スタック(Python 3.10+、最新のSciPy/ArviZには3.12+推奨)
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"

互換性に関する注意事項(2026年時点、pingouin 0.6.1、statsmodels 0.14.6、arviz 1.2で検証済み):

  • 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:SciPy 1.16+での _lazywhere インポートエラーを回避するため、statsmodels>=0.14.6 を scipy>=1.11 とともに使用します。
  • 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. データを検査する。 グループごとに:n、平均、SD、中央値、欠損値。検定の前に生データ(ヒストグラムまたは箱ひげ図)をプロットします。グループサイズの不均等、欠損、フロア/シーリング効果、外れ値はすべて適切な検定を変えます — 黙って回避するのではなく、ユーザーに明示してください。
  3. テストを選択する 以下のクイックリファレンス、または基本を超えたデザイン(度数、生存時間、信頼性、要因計画)については references/test_selection_guide.md を参照してください。
  4. 仮定をチェックする scripts/assumption_checks.py を使用します。仮定が満たされない場合は、修正検定(以下の表)に切り替え、計画と変更の両方を報告します。
  5. テストを実行し、常に効果量を一緒に計算します — p値は効果が存在することを示しますが、効果量は誰かが気にする必要があるかどうかを示します。
  6. 以下のAPAテンプレートを使用して報告する、記述統計、正確な統計量、信頼区間付きの効果量、実施した仮定チェックを含めます。

ユーザーが1つのステップだけを必要とする場合(例:「必要な参加者数は何人ですか?」)、そのセクションに直接ジャンプしても構いません — ただし、計算の前提となるデザインの仮定を確認してください。


テスト選択ガイド

クイックリファレンス:適切なテストの選択

包括的なガイダンス(度数、生存、信頼性、要因計画)については references/test_selection_guide.md を参照してください。クイックリファレンス:

2グループの比較:

  • 独立、連続、正規 → 独立したt検定
  • 独立、連続、非正規 → Mann-WhitneyのU検定
  • 対応、連続、正規 → 対応のあるt検定
  • 対応、連続、非正規 → Wilcoxonの符号付き順位検定
  • 二値結果 → カイ二乗検定またはFisherの正確確率検定

3グループ以上の比較:

  • 独立、連続、正規 → 一元配置分散分析
  • 独立、連続、非正規 → Kruskal-Wallis検定
  • 対応、連続、正規 → 反復測定分散分析
  • 対応、連続、非正規 → Friedman検定

関係:

  • 2つの連続変数 → 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スコア法
)

result = check_normality(data=df['score'], name='テストスコア', 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が大きくなるにつれて敏感になりすぎます:n ≥ 100の場合は、Shapiro-Wilkのp値よりもQ-Qプロットを重視してください。包括的なガイダンスについては 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}")

事後検定付き分散分析

import pingouin as pg

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

# 効果量:偏イータ二乗
eta_p2 = aov['np2'].values[0]

# 有意な場合、事後検定を実施(Tukey HSDは家族生得誤差を制御)
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 | データ) = {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)

事前分布はデータに合わせてスケーリングしてください(例:SDが10付近の結果には sigma=10 が適切です。観測されたSDをガイドとして使用します)。また、レポートには事前分布を明記してください。


効果量

効果量は大きさを定量化します。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は?
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: {n_required:.0f}")

# 一元配置分散分析:Cohen's f = 0.25 を検出するために必要なnは?
# 注:パラメータは k_groups、effect_size は Cohen's f (f = sqrt(eta2/(1-eta2)));
# そして solve_power はグループあたりのnではなく、TOTALサンプルサイズを返します。
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"必要な総N: {math.ceil(n_total)} (1グループあたり {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 を参照してください。


結果の報告

APAスタイルについては references/reporting_standards.md に従ってください。すべてのレポートには以下が必要です:

  1. 記述統計:すべてのグループ/変数のM、SD、n
  2. 検定統計量:検定名、統計量、df、正確なp値(p = .034、p < .05 ではない。.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) = 4.12, p < .001, d = 0.79 [95% CI: 0.38, 1.20]。

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.

関連スキル