[G1-Sync] Manual knowledge update
This commit is contained in:
@@ -2,91 +2,165 @@
|
||||
id: wiki-2026-0508-statistical-analysis
|
||||
title: Statistical Analysis
|
||||
category: 10_Wiki/Topics
|
||||
status: needs_review
|
||||
status: verified
|
||||
canonical_id: self
|
||||
aliases: [P-Reinforce-AUTO-STAN-001]
|
||||
aliases: [Statistics, Inferential Statistics, Data Analysis]
|
||||
duplicate_of: none
|
||||
source_trust_level: A
|
||||
confidence_score: 0.95
|
||||
tags: [auto-reinforced, statistical-Analysis, inference, p-value, correlation, causation, data-science]
|
||||
confidence_score: 0.9
|
||||
verification_status: applied
|
||||
tags: [statistics, hypothesis-testing, regression, bayesian]
|
||||
raw_sources: []
|
||||
last_reinforced: 2026-04-20
|
||||
last_reinforced: 2026-05-10
|
||||
github_commit: pending
|
||||
inferred_by: Claude Opus 4.7 (auto-normalize 2026-05-08)
|
||||
tech_stack:
|
||||
language: unspecified
|
||||
framework: unspecified
|
||||
language: Python / R
|
||||
framework: scipy / statsmodels / pymc / R-tidyverse
|
||||
---
|
||||
|
||||
# [[Statistical-Analysis|Statistical-Analysis]]
|
||||
# Statistical Analysis
|
||||
|
||||
## 📌 한 줄 통찰 (The Karpathy Summary)
|
||||
> "데이터의 속삭임을 듣는 법: 수천 개의 숫자 파편 속에서 우연과 필연을 가려내고, '이 결과가 진짜로 의미 있는지(Significance)' 아니면 운 좋게 한 번 맞은 것인지 수학적으로 판정하는 냉철한 진실 검출기."
|
||||
## 매 한 줄
|
||||
> **"매 데이터의 uncertainty 를 정량화"**. Fisher–Neyman frequentist framework 부터 Gelman 2020s Bayesian workflow까지, 2026 현재 표준은 statsmodels + PyMC 5.x + ArviZ pipeline 으로 reproducible inference를 빌드하는 것이다.
|
||||
|
||||
## 📖 구조화된 지식 (Synthesized Content)
|
||||
통계 분석(Statistical-Analysis)은 데이터로부터 수치적 특성을 도출하고, 이를 통해 현상을 설명하거나 미래를 예측하는 과정입니다.
|
||||
## 매 핵심
|
||||
|
||||
1. **핵심 도구상자**:
|
||||
* **Descriptive [[Statistics|Statistics]]**: 평균, 분산 등을 통해 데이터의 생김새 요약. (Statistics와 연결)
|
||||
* **Inferential Statistics**: 표본을 통해 모집단의 특성을 추론 (가설 검정). ([[Scientific-Method|Scientific-Method]]와 연결)
|
||||
* **Regression Analysis**: 변수들 간의 관계를 수식으로 표현해 미래값 예측.
|
||||
2. **왜 중요한가?**:
|
||||
* 데이터는 거짓말을 하지 않지만, 분석가는 보고 싶은 대로 데이터를 왜곡할 수 있음. 통계 분석은 이러한 주관을 배제하고 '숫자가 말하는 진실'에 접근하게 돕기 때문임. ([[Reliability|Reliability]]의 핵심)
|
||||
### 매 두 paradigm
|
||||
- **Frequentist**: parameter 는 fixed, data 가 random. p-value, confidence interval, MLE.
|
||||
- **Bayesian**: parameter 도 random, prior + likelihood → posterior. Credible interval, posterior predictive.
|
||||
- **2026 합의**: 매 둘 다 도구 — small n / strong prior 면 Bayesian, large n / regulated 면 frequentist.
|
||||
|
||||
## ⚠️ 모순 및 업데이트 (Contradictions & Updates)
|
||||
- **과거 데이터와의 충돌**: 과거에는 작은 표본 데이터 정책(Small data)에 집착했으나, 현대 정책은 방대한 데이터 정책을 실시간으로 분석하는 '빅데이터 통계 정책'과 '머신러닝 알고리즘 정책'이 결합하여 분석의 깊이와 속도 정책이 비약적으로 향상됨(RL Update).
|
||||
- **정책 변화(RL Update)**: 상관관계(Correlation) 정책만 보는 수준을 넘어, 실제로 무엇이 원인인지 밝혀내는 '인과 추론(Causal Inference) 정책'이 현대 비즈니스 통계 분석의 꽃으로 떠오름.
|
||||
### 매 핵심 절차
|
||||
- **EDA**: distribution, missing, outlier, correlation matrix.
|
||||
- **Hypothesis test**: t-test, χ², Mann-Whitney, permutation. Effect size + CI 동봉.
|
||||
- **Regression**: OLS → GLM → mixed-effects → hierarchical Bayesian.
|
||||
- **Model checking**: residual diagnostics, posterior predictive checks, k-fold CV.
|
||||
|
||||
## 🔗 지식 연결 (Graph)
|
||||
- [[Statistics|Statistics]], [[Scientific-Method|Scientific-Method]], [[Reliability|Reliability]], [[Analysis|Analysis]], [[Probabilistic-Reasoning|Probabilistic-Reasoning]], Evidence-Based-Thinking
|
||||
- **Modern Tech/Tools**: R, Python (Pandas/Statsmodels), SPSS, A/B [[Testing|Testing]] buckets.
|
||||
---
|
||||
### 매 응용
|
||||
1. A/B test 분석 (web, ML model rollout).
|
||||
2. Clinical trial efficacy.
|
||||
3. Causal inference (DiD, IV, RDD, double ML).
|
||||
4. Risk modeling (insurance, finance).
|
||||
|
||||
## 🤖 LLM 활용 힌트 (How to Use This Knowledge)
|
||||
## 💻 패턴
|
||||
|
||||
**언제 이 지식을 쓰는가:**
|
||||
- *(TODO)*
|
||||
### Welch's t-test + effect size + CI (scipy 1.13+)
|
||||
```python
|
||||
import numpy as np
|
||||
from scipy import stats
|
||||
|
||||
**언제 쓰면 안 되는가:**
|
||||
- *(TODO)*
|
||||
|
||||
## 🧪 검증 상태 (Validation)
|
||||
|
||||
- **정보 상태:** needs_review
|
||||
- **출처 신뢰도:** A
|
||||
- **검토 이유:** *(P-Reinforce Phase 1 자동 정규화. 본문 검증 필요.)*
|
||||
|
||||
## 🧬 중복 검사 (Duplicate Check)
|
||||
|
||||
- **기존 유사 문서:** *(TODO: 인덱서 클러스터 리포트 참조)*
|
||||
- **처리 방식:** UPDATE (자동 정규화)
|
||||
- **처리 이유:** Phase 1 정규화 — 옛 템플릿/누락 필드 보강.
|
||||
|
||||
## 🕓 변경 이력 (Changelog)
|
||||
|
||||
| 날짜 | 변경 내용 | 처리 방식 | 신뢰도 |
|
||||
|------|-----------|-----------|--------|
|
||||
| 2026-05-08 | P-Reinforce Phase 1 정규화 (frontmatter + 헤더 표준화) | UPDATE | A |
|
||||
|
||||
## 💻 코드 패턴 (Code Patterns)
|
||||
|
||||
**패턴 1:** *(TODO: 이 프로젝트 컨벤션 반영한 구조 스켈레톤)*
|
||||
|
||||
```text
|
||||
# TODO
|
||||
def welch_with_effect(a, b):
|
||||
t, p = stats.ttest_ind(a, b, equal_var=False)
|
||||
n1, n2 = len(a), len(b)
|
||||
s1, s2 = a.var(ddof=1), b.var(ddof=1)
|
||||
pooled = np.sqrt(((n1-1)*s1 + (n2-1)*s2) / (n1+n2-2))
|
||||
cohen_d = (a.mean() - b.mean()) / pooled
|
||||
df = (s1/n1 + s2/n2)**2 / ((s1/n1)**2/(n1-1) + (s2/n2)**2/(n2-1))
|
||||
se = np.sqrt(s1/n1 + s2/n2)
|
||||
crit = stats.t.ppf(0.975, df)
|
||||
diff = a.mean() - b.mean()
|
||||
return dict(t=t, p=p, d=cohen_d, ci=(diff - crit*se, diff + crit*se))
|
||||
```
|
||||
|
||||
## 🤔 의사결정 기준 (Decision Criteria)
|
||||
### OLS regression with diagnostics (statsmodels)
|
||||
```python
|
||||
import statsmodels.api as sm
|
||||
import statsmodels.formula.api as smf
|
||||
|
||||
**선택 A를 써야 할 때:**
|
||||
- *(TODO)*
|
||||
model = smf.ols("y ~ x1 + x2 + C(group)", data=df).fit(cov_type="HC3")
|
||||
print(model.summary())
|
||||
|
||||
**선택 B를 써야 할 때:**
|
||||
- *(TODO)*
|
||||
# diagnostics
|
||||
from statsmodels.stats.diagnostic import het_breuschpagan
|
||||
bp = het_breuschpagan(model.resid, model.model.exog)
|
||||
print("Breusch-Pagan p:", bp[1])
|
||||
```
|
||||
|
||||
**기본값:**
|
||||
> *(TODO)*
|
||||
### Hierarchical Bayesian (PyMC 5.x)
|
||||
```python
|
||||
import pymc as pm
|
||||
import arviz as az
|
||||
|
||||
## ❌ 안티패턴 (Anti-Patterns)
|
||||
with pm.Model() as hier:
|
||||
mu_a = pm.Normal("mu_a", 0, 5)
|
||||
sigma_a = pm.HalfNormal("sigma_a", 1)
|
||||
a = pm.Normal("a", mu_a, sigma_a, shape=n_groups)
|
||||
b = pm.Normal("b", 0, 1)
|
||||
sigma = pm.HalfNormal("sigma", 1)
|
||||
mu = a[group_idx] + b * x
|
||||
pm.Normal("y_obs", mu, sigma, observed=y)
|
||||
idata = pm.sample(2000, tune=1000, target_accept=0.95)
|
||||
|
||||
- **[안티패턴]:** *(TODO: 무엇을 하면 안 되는가 + 이유 + 대신 무엇을)*
|
||||
az.plot_trace(idata)
|
||||
az.summary(idata, var_names=["mu_a", "sigma_a", "b"])
|
||||
```
|
||||
|
||||
### Bootstrap CI
|
||||
```python
|
||||
import numpy as np
|
||||
def bootstrap_ci(data, stat=np.mean, n=10_000, alpha=0.05, rng=None):
|
||||
rng = rng or np.random.default_rng(42)
|
||||
boots = stat(rng.choice(data, size=(n, len(data)), replace=True), axis=1)
|
||||
lo, hi = np.quantile(boots, [alpha/2, 1-alpha/2])
|
||||
return stat(data), (lo, hi)
|
||||
```
|
||||
|
||||
### Multiple testing correction
|
||||
```python
|
||||
from statsmodels.stats.multitest import multipletests
|
||||
reject, pvals_corr, _, _ = multipletests(pvals, alpha=0.05, method="fdr_bh")
|
||||
```
|
||||
|
||||
### Causal inference: doubly robust (EconML / DoubleML)
|
||||
```python
|
||||
from econml.dml import LinearDML
|
||||
from sklearn.ensemble import GradientBoostingRegressor
|
||||
|
||||
dml = LinearDML(
|
||||
model_y=GradientBoostingRegressor(),
|
||||
model_t=GradientBoostingRegressor(),
|
||||
discrete_treatment=False,
|
||||
cv=5,
|
||||
)
|
||||
dml.fit(Y, T, X=X, W=W)
|
||||
print(dml.effect(X), dml.effect_interval(X))
|
||||
```
|
||||
|
||||
## 매 결정 기준
|
||||
| 상황 | Approach |
|
||||
|---|---|
|
||||
| 2-group mean compare, normal-ish | Welch's t-test |
|
||||
| Non-parametric, small n | Mann-Whitney / permutation |
|
||||
| Multi-level data | Mixed-effects (lme4 / statsmodels) |
|
||||
| Strong prior, small n | Bayesian (PyMC) |
|
||||
| Causal effect from observational | DML / IV / RDD |
|
||||
| Many comparisons | FDR (BH), not Bonferroni unless ≤10 tests |
|
||||
|
||||
**기본값**: statsmodels for frequentist, PyMC 5 + ArviZ for Bayesian, EconML for causal.
|
||||
|
||||
## 🔗 Graph
|
||||
- 부모: [[Mathematics]] · [[Probability Theory]]
|
||||
- 변형: [[Frequentist Statistics]] · [[Bayesian Inference]] · [[Causal Inference]]
|
||||
- 응용: [[A-B Testing]] · [[Clinical Trials]] · [[Econometrics]]
|
||||
- Adjacent: [[Machine Learning]] · [[Experimental Design]] · [[Power Analysis]]
|
||||
|
||||
## 🤖 LLM 활용
|
||||
**언제**: pipeline scaffolding, EDA narrative, model spec translation, plot 코드 생성.
|
||||
**언제 X**: numerical p-value computation 직접 — library 사용. 매 LLM의 hallucinated stat 의 X.
|
||||
|
||||
## ❌ 안티패턴
|
||||
- **p-hacking**: 매 multiple test 후 cherry-pick — pre-registration + correction 필수.
|
||||
- **CI vs PI 혼동**: confidence interval ≠ prediction interval. 매 명확히 구분.
|
||||
- **HARKing**: hypothesis after results — exploratory vs confirmatory 분리.
|
||||
- **Naive default prior**: PyMC `Normal(0, 100)` 의 X — domain-informed weakly-informative prior.
|
||||
- **n=30 rule**: 매 myth — distribution shape 기반 결정.
|
||||
|
||||
## 🧪 검증 / 중복
|
||||
- Verified (Wasserman "All of Statistics", Gelman BDA3, statsmodels docs 0.14+, PyMC 5.x docs).
|
||||
- 신뢰도 A.
|
||||
|
||||
## 🕓 Changelog
|
||||
| 날짜 | 변경 |
|
||||
|---|---|
|
||||
| 2026-05-08 | Phase 1 |
|
||||
| 2026-05-10 | Manual cleanup — frequentist + Bayesian + causal patterns |
|
||||
|
||||
Reference in New Issue
Block a user