[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,62 +2,185 @@
id: wiki-2026-0508-linear-regression-mastery
title: Linear Regression Mastery
category: 10_Wiki/Topics
status: needs_review
status: verified
canonical_id: self
aliases: [ML-LIN-REG-001]
aliases: [Linear Regression, OLS, Ordinary Least Squares, Ridge, Lasso]
duplicate_of: none
source_trust_level: A
confidence_score: 1.0
tags: [machine-learning, linear-regression, regression, Supervised-Learning, Statistics]
confidence_score: 0.9
verification_status: applied
tags: [machine-learning, regression, statistics, sklearn, ols, ridge, lasso]
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: scikit-learn/statsmodels
---
# Linear Regression [[Mastery|Mastery]] (선형 회귀 마스터리)
# Linear Regression Mastery
## 📌 한 줄 통찰 (The Karpathy Summary)
> "데이터들의 복잡한 흩어짐 속에서 변치 않는 '비례의 법칙'을 찾아내어 미래를 투영하라" — 입력값(Features)과 출력값(Target) 사이의 관계를 가장 잘 설명하는 일차 방정식(직선 또는 초평면)을 찾아내는 지도 학습의 근본 알고리즘.
## 한 줄
> **"매 모든 ML의 출발점 — y = Xβ + ε"**. Linear regression은 feature와 target의 선형 관계를 OLS로 추정하는 모델. 단순함 덕분에 해석성·속도·baseline으로 강하며, regularization (Ridge/Lasso/Elastic Net)으로 high-dim에서도 살아남는다. 2026 시대에도 production tabular ML의 절반은 여전히 linear.
## 📖 구조화된 지식 (Synthesized Content)
- **추출된 패턴:** "Linear Approximation" — 변수들 간의 관계가 선형적이라는 가정하에, 오차의 제곱합을 최소화하는 기울기(Weights)와 절편(Bias)을 구하여 연속적인 수치를 예측하는 수치 추론 패턴.
- **핵심 요소:**
- **Hypothesis:** $y = w_1x_1 + ... + w_nx_n + b$ 형태의 예측 함수.
- **Cost Function:** 예측값과 실제값의 차이를 측정하는 MSE(Mean Squared Error).
- **Optimizer:** 비용 함수를 최소화하기 위한 경사 하강법(Gradient Descent) 또는 정규 방정식.
- **의의:** 결과에 대한 해석력이 매우 뛰어나며(Coefficients 분석), 인공지능이 데이터를 통해 '학습'한다는 개념을 이해하기 위한 가장 중요한 출발점.
## 매 핵심
## ⚠️ 모순 및 업데이트 (Contradictions & Updates)
- **과거 데이터와의 충돌:** 단순한 직선 찾기로 치부되기도 했으나, 정규화(L1/L2)나 다항 회귀(Polynomial) 등을 통해 복잡한 데이터에도 유연하게 대응하며 현대 딥러닝 뉴런의 기본 단위로 계승됨.
- **정책 변화:** Antigravity 프로젝트는 시스템 리소스 사용량 예측 및 지식 강화 작업 소요 시간 추정 시, 가장 신뢰도 높은 해석을 제공하는 선형 회귀 모델을 기본 지표로 사용함.
### 매 OLS 수식
- 모델: $y = X\beta + \varepsilon$.
- 목적: $\min_\beta \|y - X\beta\|^2$.
- 닫힌해: $\hat\beta = (X^TX)^{-1}X^Ty$ (X full-rank일 때).
- 기하적: y를 column space of X에 projection.
## 🔗 지식 연결 (Graph)
- [[Least-Squares-Methods|Least-Squares-Methods]], [[Gradient-Descent|Gradient-Descent]]-Foundations, [[L1-and-L2-Regularization|L1-and-L2-Regularization]], [[Supervised-Learning-Foundations|Supervised-Learning-Foundations]]
- **Raw Source:** 10_Wiki/Topics/AI/Linear-Regression-Mastery.md
### 매 가정 (LINE)
- **L**inearity: y와 X의 관계가 선형.
- **I**ndependence: 잔차 i.i.d.
- **N**ormality: 잔차 ~ N(0, σ²) (소표본일 때 inference에 필요).
- **E**qual variance (homoscedasticity): 잔차 분산 일정.
- **추가**: No multicollinearity (X feature 간 상관 낮음).
## 🤖 LLM 활용 힌트 (How to Use This Knowledge)
### 매 Regularized 변종
- **Ridge (L2)**: $\min \|y-X\beta\|^2 + \lambda\|\beta\|_2^2$ — 모든 계수 작게.
- **Lasso (L1)**: $\min \|y-X\beta\|^2 + \lambda\|\beta\|_1$ — sparsity (feature selection).
- **Elastic Net**: L1 + L2 — 상관된 feature 그룹 처리.
**언제 이 지식을 쓰는가:**
- *(TODO)*
### 매 진단
- R² / Adjusted R²: 설명력.
- RMSE / MAE: 예측 오차.
- VIF > 10: multicollinearity 의심.
- Residual plot: 패턴 있으면 비선형.
- QQ plot: normality 체크.
- Cook's distance: 영향력 큰 outlier.
**언제 쓰면 안 되는가:**
- *(TODO)*
### 매 응용
1. Tabular baseline (어떤 ML이든 첫 모델).
2. Feature 영향 해석 (coefficient).
3. Time-series trend.
4. A/B test effect size.
5. Causal inference (DiD, IV)의 backbone.
## 🧪 검증 상태 (Validation)
## 💻 패턴
- **정보 상태:** needs_review
- **출처 신뢰도:** A
- **검토 이유:** *(P-Reinforce Phase 1 자동 정규화. 본문 검증 필요.)*
### sklearn — 기본 OLS
```python
from sklearn.linear_model import LinearRegression
from sklearn.model_selection import train_test_split
from sklearn.metrics import mean_squared_error, r2_score
import numpy as np
## 🧬 중복 검사 (Duplicate Check)
X_tr, X_te, y_tr, y_te = train_test_split(X, y, test_size=0.2, random_state=42)
model = LinearRegression().fit(X_tr, y_tr)
pred = model.predict(X_te)
print("R²:", r2_score(y_te, pred), "RMSE:", np.sqrt(mean_squared_error(y_te, pred)))
print("coef:", dict(zip(feature_names, model.coef_)))
```
- **기존 유사 문서:** *(TODO: 인덱서 클러스터 리포트 참조)*
- **처리 방식:** UPDATE (자동 정규화)
- **처리 이유:** Phase 1 정규화 — 옛 템플릿/누락 필드 보강.
### Ridge / Lasso / ElasticNet — CV로 alpha 선택
```python
from sklearn.linear_model import RidgeCV, LassoCV, ElasticNetCV
from sklearn.preprocessing import StandardScaler
from sklearn.pipeline import Pipeline
## 🕓 변경 이력 (Changelog)
ridge = Pipeline([("sc", StandardScaler()),
("m", RidgeCV(alphas=np.logspace(-3, 3, 50), cv=5))]).fit(X_tr, y_tr)
lasso = Pipeline([("sc", StandardScaler()),
("m", LassoCV(cv=5, max_iter=10000))]).fit(X_tr, y_tr)
en = Pipeline([("sc", StandardScaler()),
("m", ElasticNetCV(l1_ratio=[.1,.5,.7,.9,.95,1], cv=5))]).fit(X_tr, y_tr)
print("ridge alpha:", ridge.named_steps["m"].alpha_)
print("lasso non-zero:", (lasso.named_steps["m"].coef_ != 0).sum())
```
| 날짜 | 변경 내용 | 처리 방식 | 신뢰도 |
|------|-----------|-----------|--------|
| 2026-05-08 | P-Reinforce Phase 1 정규화 (frontmatter + 헤더 표준화) | UPDATE | A |
### statsmodels — 통계적 추론 (p-value, CI)
```python
import statsmodels.api as sm
X_const = sm.add_constant(X_tr)
ols = sm.OLS(y_tr, X_const).fit()
print(ols.summary()) # coef, std-err, t, p, [95% CI]
print("Cond no:", ols.condition_number) # >30 multicollinearity 의심
```
### 진단 — VIF + residual plot
```python
from statsmodels.stats.outliers_influence import variance_inflation_factor
import matplotlib.pyplot as plt
vif = [variance_inflation_factor(X_tr.values, i) for i in range(X_tr.shape[1])]
print(dict(zip(X_tr.columns, vif))) # >10이면 제거 또는 PCA
resid = y_tr - model.predict(X_tr)
plt.scatter(model.predict(X_tr), resid, alpha=.4); plt.axhline(0)
plt.xlabel("fitted"); plt.ylabel("residual"); plt.show()
```
### Polynomial features (비선형 처리)
```python
from sklearn.preprocessing import PolynomialFeatures
poly = PolynomialFeatures(degree=2, interaction_only=False, include_bias=False)
Xp_tr = poly.fit_transform(X_tr)
Pipeline([("sc", StandardScaler()),
("m", RidgeCV())]).fit(Xp_tr, y_tr) # 항상 Ridge — 차원 폭증
```
### Bayesian linear regression — PyMC
```python
import pymc as pm
with pm.Model() as m:
β = pm.Normal("β", 0, 10, shape=X_tr.shape[1])
α = pm.Normal("α", 0, 10)
σ = pm.HalfNormal("σ", 5)
y_obs = pm.Normal("y", α + X_tr.values @ β, σ, observed=y_tr)
trace = pm.sample(1000, tune=1000, chains=4)
pm.summary(trace, hdi_prob=0.95)
```
### From scratch — gradient descent
```python
import numpy as np
def fit_gd(X, y, lr=1e-2, epochs=2000, l2=0.0):
n, d = X.shape
X_ = np.c_[np.ones(n), X]
w = np.zeros(d + 1)
for _ in range(epochs):
grad = -2/n * X_.T @ (y - X_ @ w) + 2*l2 * np.r_[0, w[1:]]
w -= lr * grad
return w[0], w[1:]
```
## 매 결정 기준
| 상황 | Approach |
|---|---|
| Baseline 빠르게 | OLS |
| Multicollinearity / p>>n | Ridge |
| Feature selection 원함 | Lasso |
| 상관된 feature 그룹 | Elastic Net |
| 비선형 의심 | Polynomial + Ridge or move to tree |
| 통계적 추론 (p-value) | statsmodels |
**기본값**: StandardScaler + RidgeCV — 안전, 해석 가능, 빠름.
## 🔗 Graph
- 부모: [[Supervised-Learning]], [[Regression]]
- 변형: [[Ridge-Regression]], [[Lasso-Regression]], [[Elastic-Net]], [[Logistic-Regression-Foundations]]
- 응용: [[Time-Series-Forecasting]], [[A-B-Testing]], [[Causal-Inference]]
- Adjacent: [[L1-and-L2-Regularization]], [[Feature-Engineering]], [[Cross-Validation]]
## 🤖 LLM 활용
**언제**: feature engineering ideation, residual plot 해석, statsmodels output 설명.
**언제 X**: 데이터 자체의 outlier 판단 — 도메인 지식 필요.
## ❌ 안티패턴
- **Scaling 안 함**: Ridge/Lasso는 scale에 민감.
- **VIF 무시**: coefficient 부호 뒤집힘.
- **R² 만 보고 판단**: 과적합 못 잡음 — adjusted R² 또는 CV 사용.
- **잔차 plot 안 봄**: 비선형성 놓침.
- **소표본에 polynomial deg 5+**: 폭주, overfit.
## 🧪 검증 / 중복
- Verified (ESL Hastie/Tibshirani, sklearn 1.5+, statsmodels 0.14).
- 신뢰도 A.
## 🕓 Changelog
| 날짜 | 변경 |
|---|---|
| 2026-05-08 | Phase 1 |
| 2026-05-10 | Manual cleanup — Ridge/Lasso/EN, 진단, Bayesian 추가 |