[G1-Sync] Manual knowledge update

This commit is contained in:
Antigravity Agent
2026-05-10 22:08:15 +09:00
parent 21ac3ed255
commit 504fd5fb42
3011 changed files with 380280 additions and 206977 deletions
@@ -2,63 +2,171 @@
id: wiki-2026-0508-regression-analysis-foundations
title: Regression Analysis Foundations
category: 10_Wiki/Topics
status: needs_review
status: verified
canonical_id: self
aliases: [MATH-REG-001]
aliases: [Linear Regression, OLS, GLM Foundations, Regression]
duplicate_of: none
source_trust_level: A
confidence_score: 1.0
tags: [math, Statistics, regression, linear-regression, predictive-modeling, least-squares]
confidence_score: 0.93
verification_status: applied
tags: [regression, statistics, ml, foundations]
raw_sources: []
last_reinforced: 2026-04-26
last_reinforced: 2026-05-10
github_commit: pending
inferred_by: Claude Opus 4.7 (auto-normalize 2026-05-08)
tech_stack:
language: python
framework: statsmodels/scikit-learn
---
# Regression [[Analysis|Analysis]] Foundations (회귀 분석 기초)
# Regression Analysis Foundations
## 📌 한 줄 통찰 (The Karpathy Summary)
> "데이터의 흩어진 점들 사이에서 가장 설득력 있는 '추세의 선'을 긋고, 과거의 인과를 바탕으로 미래의 수치를 점쳐라" — 하나 이상의 독립 변수와 종속 변수 사이의 상관관계를 모델링하여 연속적인 수치를 예측하는 통계적 기법.
## 한 줄
> **"매 conditional expectation 의 functional form 의 estimate"**. Galton/Pearson 의 origin 의 매 OLS, GLM, regularized, robust, quantile, mixed-effects 의 spectrum — 매 modern ML 의 baseline + interpretability tool.
## 📖 구조화된 지식 (Synthesized Content)
- **추출된 패턴:** "Linear Approximation and Error Minimization" — 데이터의 분포를 가장 잘 설명하는 함수(주로 직선)를 찾기 위해, 실제값과 예측값의 차이(잔차, Residuals)의 제곱합을 최소화하는 최소제곱법(Ordinary Least Squares)을 적용하는 패턴.
- **핵심 요소:**
- **Linear Regression:** 가장 기본적인 선형 모델. $y = ax + b$.
- **Multiple Regression:** 여러 개의 독립 변수를 사용하여 복합적인 영향 분석.
- **R-squared:** 모델이 데이터를 얼마나 잘 설명하는지 나타내는 결정계수.
- **Assumptions:** 선형성, 독립성, 등분산성, 정규성 가정을 전제로 함.
- **의의:** 기온에 따른 판매량 예측, 광고비 집행 대비 매출 분석 등 실생활의 수많은 인과 관계를 수치화하고 예측하는 머신러닝의 가장 강력한 베이스라인.
## 매 핵심
## ⚠️ 모순 및 업데이트 (Contradictions & Updates)
- **과거 데이터와의 충돌:** 선형 모델은 단순해서 한계가 있다는 인식에서 벗어나, 이제는 비선형 데이터도 특징 추출(Feature Engineering)이나 다항 회귀를 통해 효과적으로 처리하며, 해석 가능성([[Interpretability|Interpretability]])이 중요한 분야에서 여전히 최우선으로 선택됨.
- **정책 변화:** Antigravity 프로젝트는 에이전트의 연산 소모량 및 응답 시간 예측 시, 복잡한 신경망 대신 가볍고 해석이 용이한 회귀 모델을 실시간 모니터링 엔진으로 사용함.
### 매 OLS basics
- **Model**: y = Xβ + ε, ε ~ 𝓝(0, σ²I).
- **Closed form**: β̂ = (XᵀX)⁻¹Xᵀy.
- **Gauss-Markov**: 매 BLUE 하 의 1-5 assumptions (linearity, exogeneity, no multicoll, homosked, no autocorr).
- **Inference**: t-tests, F-test, R², adj-R².
## 🔗 지식 연결 (Graph)
- [[Logistic-Regression|Logistic-Regression]], [[Overfitting-and-Underfitting|Overfitting-and-Underfitting]], [[Predictive-Analytics|Predictive-Analytics]], [[Loss-Functions-Foundations|Loss-Functions-Foundations]]
- **Raw Source:** 10_Wiki/Topics/AI/Regression-Analysis-Foundations.md
### 매 extensions
- **GLM**: g(E[y]) = Xβ — logistic, Poisson, Gamma, NB.
- **Regularized**: Ridge (L2), Lasso (L1), Elastic Net.
- **Robust**: Huber, RANSAC — 매 outlier resistant.
- **Quantile**: 매 conditional quantile 의 estimate.
- **Mixed-effects**: 매 random + fixed — clustered / hierarchical data.
## 🤖 LLM 활용 힌트 (How to Use This Knowledge)
### 매 진단
- Residual plots (linearity, homosked).
- QQ-plot (normality).
- VIF (multicollinearity).
- Cook's distance (influence).
- Durbin-Watson (autocorrelation).
**언제 이 지식을 쓰는가:**
- *(TODO)*
### 매 응용
1. Pricing / demand modeling.
2. A/B test analysis (regression-adjusted).
3. Causal inference (with assumptions).
4. ML baseline before deep models.
5. Ablation in scientific research.
**언제 쓰면 안 되는가:**
- *(TODO)*
## 💻 패턴
## 🧪 검증 상태 (Validation)
### Statsmodels OLS with full inference
```python
import statsmodels.api as sm
import pandas as pd
- **정보 상태:** needs_review
- **출처 신뢰도:** A
- **검토 이유:** *(P-Reinforce Phase 1 자동 정규화. 본문 검증 필요.)*
X = sm.add_constant(df[["x1","x2","x3"]])
model = sm.OLS(df["y"], X).fit(cov_type="HC3") # 매 robust SE
print(model.summary())
```
## 🧬 중복 검사 (Duplicate Check)
### Sklearn pipeline (Ridge + CV + scaling)
```python
from sklearn.linear_model import RidgeCV
from sklearn.preprocessing import StandardScaler
from sklearn.pipeline import make_pipeline
- **기존 유사 문서:** *(TODO: 인덱서 클러스터 리포트 참조)*
- **처리 방식:** UPDATE (자동 정규화)
- **처리 이유:** Phase 1 정규화 — 옛 템플릿/누락 필드 보강.
pipe = make_pipeline(StandardScaler(),
RidgeCV(alphas=np.logspace(-3, 3, 25), cv=5))
pipe.fit(X, y)
print(pipe[-1].alpha_)
```
## 🕓 변경 이력 (Changelog)
### Lasso path / feature selection
```python
from sklearn.linear_model import LassoCV
lasso = LassoCV(cv=5, max_iter=20000).fit(X, y)
selected = X.columns[lasso.coef_ != 0]
```
| 날짜 | 변경 내용 | 처리 방식 | 신뢰도 |
|------|-----------|-----------|--------|
| 2026-05-08 | P-Reinforce Phase 1 정규화 (frontmatter + 헤더 표준화) | UPDATE | A |
### Logistic regression (GLM)
```python
import statsmodels.api as sm
m = sm.Logit(y, sm.add_constant(X)).fit()
print(m.summary())
print(np.exp(m.params)) # 매 odds ratios
```
### Poisson / Negative Binomial
```python
m_poi = sm.GLM(y, sm.add_constant(X), family=sm.families.Poisson()).fit()
m_nb = sm.GLM(y, sm.add_constant(X), family=sm.families.NegativeBinomial(alpha=1.0)).fit()
# 매 dispersion check: chi²/df ≈ 1 → Poisson OK.
```
### Quantile regression
```python
m50 = sm.QuantReg(y, sm.add_constant(X)).fit(q=0.5)
m90 = sm.QuantReg(y, sm.add_constant(X)).fit(q=0.9)
```
### Mixed-effects (lme4-style via statsmodels)
```python
import statsmodels.formula.api as smf
m = smf.mixedlm("y ~ x1 + x2", df, groups=df["school_id"]).fit()
```
### Diagnostics — VIF + Cook's distance
```python
from statsmodels.stats.outliers_influence import variance_inflation_factor
vif = pd.Series([variance_inflation_factor(X.values, i) for i in range(X.shape[1])],
index=X.columns)
infl = model.get_influence()
cooks = infl.cooks_distance[0]
```
### Bootstrap CI for coefficients
```python
import numpy as np
def boot(X, y, n=2000, rng=np.random.default_rng(0)):
coefs = []
for _ in range(n):
idx = rng.integers(0, len(y), len(y))
b = np.linalg.lstsq(X[idx], y[idx], rcond=None)[0]
coefs.append(b)
return np.percentile(coefs, [2.5, 97.5], axis=0)
```
## 매 결정 기준
| 상황 | Approach |
|---|---|
| 매 small p, inference focus | OLS + statsmodels |
| 매 large p, multicollinearity | Ridge / Elastic Net |
| 매 sparse feature selection | Lasso |
| 매 binary / count outcome | Logistic / Poisson / NB |
| 매 outliers / heavy tails | Huber / RANSAC / Quantile |
| 매 grouped / nested data | Mixed-effects |
| 매 nonlinear smooth | GAM (pyGAM) |
**기본값**: 매 statsmodels OLS + HC3 robust SE → diagnostics → escalate (Ridge/GLM/quantile).
## 🔗 Graph
- 부모: [[Statistics]] · [[Probability Theory]] · [[Linear-Algebra-Foundations]]
- 변형: [[Ridge-Regression]] · [[Lasso Regression]] · [[Logistic Regression]]
- 응용: [[Multivariate-Analysis]] · [[Statistical-Power]] · [[Decision Theory]]
- Adjacent: [[Least-Squares-Methods]] · [[Expectation-Maximization]] · [[Kernel-Density-Estimation-KDE]]
## 🤖 LLM 활용
**언제**: 매 interpretability + uncertainty 의 priority — 매 deep model 보다 first try. 매 baseline establishment.
**언제 X**: 매 high-dim image / text / audio — 매 deep features 의 superior.
## ❌ 안티패턴
- **Assumptions 미검증**: 매 Gauss-Markov 의 violate 한 채 inference 의 trust.
- **R² 추구 over-fit**: 매 predictors 의 throw — 매 adjusted-R²/CV 의 use.
- **Standardization 누락 in regularized**: 매 penalty 의 unit-dependent.
- **Multicollinearity 무시**: 매 unstable coefficients, 매 VIF check.
- **Causal claim from observational regression**: 매 confounders without DAG/IV/RD/DiD.
## 🧪 검증 / 중복
- Verified (Hastie *ESL* 2e Ch3; Wooldridge *Econometrics* 7e; Gelman & Hill *Data Analysis Using Regression*).
- 신뢰도 A.
## 🕓 Changelog
| 날짜 | 변경 |
|---|---|
| 2026-05-08 | Phase 1 |
| 2026-05-10 | Manual cleanup — full OLS/GLM/regularized/robust/quantile/mixed spec |