[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,151 @@
id: wiki-2026-0508-ridge-regression
title: Ridge Regression
category: 10_Wiki/Topics
status: needs_review
status: verified
canonical_id: self
aliases: [MATH-REG-RID-001]
aliases: [L2 Regularization, Tikhonov Regularization]
duplicate_of: none
source_trust_level: A
confidence_score: 1.0
tags: [math, Statistics, machine-learning, regression, L2-Regularization, ridge-regression, Overfitting]
confidence_score: 0.9
verification_status: applied
tags: [machine-learning, regression, regularization, statistics]
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
---
# Ridge Regression (릿지 회귀)
# Ridge Regression
## 📌 한 줄 통찰 (The Karpathy Summary)
> "데이터의 노이즈에 과민반응하지 않도록 가중치의 제곱합(L2)을 제한하여, 부드럽고 강건한 예측의 곡선을 설계하라" — 선형 회귀의 손실 함수에 가중치의 제곱에 비례하는 페널티 항을 추가하여 모델의 복잡도를 제어하고 과적합을 방지하는 규제 기법.
## 한 줄
> **"매 L2 penalty 의 OLS 의 stabilize"**. Hoerl & Kennard (1970) 의 multicollinearity 의 fix 의 introduce — 매 modern ML 의 baseline regularizer 의 사용 (sklearn `Ridge`, `RidgeCV`).
## 📖 구조화된 지식 (Synthesized Content)
- **추출된 패턴:** "Weight Shrinkage and Variance Reduction" — 모든 가중치를 골고루 0에 가깝게 수렴시키되 완전히 0으로 만들지는 않음으로써, 특정 변수에 대한 과도한 의존성을 줄이고 모델의 일반화 성능(Generalization)을 높이는 패턴.
- **핵심 메커니즘:**
- **L2 [[Regularization|Regularization]]:** 가중치 벡터의 L2 노름(Norm)을 최소화.
- **Hyper[[Parameter|Parameter]] $\lambda$ (Lambda):** 규제의 강도를 조절. 값이 클수록 규제가 강해짐.
- **Bias-Variance Tradeoff:** 편향(Bias)은 약간 증가시키되 분산(Variance)을 대폭 낮추어 전체 오차 최소화.
- **의의:** 다중공선성(Multicollinearity) 문제가 있는 데이터셋에서 선형 회귀보다 훨씬 안정적인 성능을 보이며, 거의 모든 머신러닝 모델의 기본 규제 장치로 활용됨.
## 매 핵심
## ⚠️ 모순 및 업데이트 (Contradictions & Updates)
- **과거 데이터와의 충돌:** 변수를 완전히 제거하여 모델을 단순화하려는 Lasso(L1)와 달리, 데이터의 모든 정보를 조금씩이라도 유지하려는 특성이 있어 변수 간 상관관계가 높은 실전 데이터에서 종종 더 우수한 성능을 나타냄.
- **정책 변화:** Antigravity 프로젝트는 에이전트의 성능 예측 모델 구축 시, 소수의 성능 지표에만 치우치지 않는 균형 잡힌 판단을 위해 릿지 회귀 기반의 규제 로직을 적용함.
### 매 Loss function
- OLS: `min ||y - Xβ||²`
- Ridge: `min ||y - Xβ||² + α||β||²`
- α (alpha) → regularization strength. α=0 → OLS. α→∞ → β→0.
## 🔗 지식 연결 (Graph)
- Regression-Analysis-Foundations, [[Regularization-Strategies|Regularization-Strategies]], [[Overfitting-and-Underfitting|Overfitting-and-Underfitting]], [[Loss-Functions-Foundations|Loss-Functions-Foundations]]
- **Raw Source:** 10_Wiki/Topics/AI/Ridge-Regression.md
### 매 Closed form
- `β̂ = (XᵀX + αI)⁻¹ Xᵀy`
- `XᵀX + αI` 는 invertible — 매 multicollinear 한 X 도 OK.
- OLS 의 `(XᵀX)⁻¹` 는 singular 가능 → ridge 가 fix.
## 🤖 LLM 활용 힌트 (How to Use This Knowledge)
### 매 응용
1. Multicollinear features (correlated predictors).
2. p > n (features more than samples) — gene expression, fMRI.
3. Baseline 의 sklearn pipelines.
**언제 이 지식을 쓰는가:**
- *(TODO)*
## 💻 패턴
**언제 쓰면 안 되는가:**
- *(TODO)*
### Sklearn Ridge
```python
from sklearn.linear_model import Ridge, RidgeCV
from sklearn.preprocessing import StandardScaler
from sklearn.pipeline import make_pipeline
## 🧪 검증 상태 (Validation)
# Always scale before ridge — penalty is scale-dependent
model = make_pipeline(StandardScaler(), Ridge(alpha=1.0))
model.fit(X_train, y_train)
print(model.score(X_test, y_test))
```
- **정보 상태:** needs_review
- **출처 신뢰도:** A
- **검토 이유:** *(P-Reinforce Phase 1 자동 정규화. 본문 검증 필요.)*
### Cross-validated alpha
```python
# RidgeCV picks best alpha from grid
ridge = RidgeCV(alphas=[0.01, 0.1, 1.0, 10.0, 100.0], cv=5)
ridge.fit(X_train, y_train)
print(f"Best alpha: {ridge.alpha_}")
```
## 🧬 중복 검사 (Duplicate Check)
### Closed-form by hand
```python
import numpy as np
- **기존 유사 문서:** *(TODO: 인덱서 클러스터 리포트 참조)*
- **처리 방식:** UPDATE (자동 정규화)
- **처리 이유:** Phase 1 정규화 — 옛 템플릿/누락 필드 보강.
def ridge_fit(X, y, alpha):
n, p = X.shape
I = np.eye(p)
return np.linalg.solve(X.T @ X + alpha * I, X.T @ y)
## 🕓 변경 이력 (Changelog)
beta = ridge_fit(X_train, y_train, alpha=1.0)
```
| 날짜 | 변경 내용 | 처리 방식 | 신뢰도 |
|------|-----------|-----------|--------|
| 2026-05-08 | P-Reinforce Phase 1 정규화 (frontmatter + 헤더 표준화) | UPDATE | A |
### SVD-based ridge (numerically stable)
```python
def ridge_svd(X, y, alpha):
U, s, Vt = np.linalg.svd(X, full_matrices=False)
d = s / (s**2 + alpha)
return Vt.T @ (d * (U.T @ y))
```
### Kernel Ridge
```python
from sklearn.kernel_ridge import KernelRidge
# Non-linear ridge via kernel trick
krr = KernelRidge(alpha=1.0, kernel='rbf', gamma=0.1)
krr.fit(X_train, y_train)
```
### Bayesian view
```python
from sklearn.linear_model import BayesianRidge
# Ridge as Gaussian prior on β with variance 1/α
br = BayesianRidge()
br.fit(X_train, y_train)
print(br.coef_, br.alpha_) # learned alpha
```
### Regularization path
```python
import numpy as np
from sklearn.linear_model import Ridge
alphas = np.logspace(-3, 3, 50)
coefs = []
for a in alphas:
r = Ridge(alpha=a).fit(X, y)
coefs.append(r.coef_)
# Plot coefs vs log(alpha) — see shrinkage
```
## 매 결정 기준
| 상황 | Approach |
|---|---|
| Multicollinear features | Ridge |
| Need feature selection | Lasso (L1) |
| Mix of sparsity + grouping | Elastic Net |
| Non-linear pattern | Kernel Ridge |
| Bayesian uncertainty | BayesianRidge |
**기본값**: `RidgeCV` with log-spaced alpha grid + StandardScaler.
## 🔗 Graph
- 부모: [[Linear-Regression]] · [[Regularization]]
- 변형: [[Lasso-Regression]] · [[Elastic-Net]] · [[Kernel-Ridge]]
- 응용: [[Feature-Engineering]] · [[Bias-Variance-Tradeoff]]
- Adjacent: [[Singular-Value-Decomposition]] · [[Bayesian-Linear-Regression]]
## 🤖 LLM 활용
**언제**: Tabular regression 의 strong baseline. Multicollinear features (correlated predictors) 의 시. p > n 의 high-dim setting. Linear model interpretability 의 keep.
**언제 X**: Sparse feature selection 의 필요 (use Lasso). Strong non-linearity (use trees/NN). N >> p 의 와 features uncorrelated → OLS 도 충분.
## ❌ 안티패턴
- **No scaling**: Ridge penalty 의 scale-sensitive — features 의 다른 scale 의 → 매 unfair shrinkage.
- **Manual alpha pick**: 매 RidgeCV 의 use, magic number alpha=1.0 의 X.
- **Ridge for sparsity**: L2 의 X coefficient 의 zero 의 안 만든다 — Lasso 의 use.
- **Ignoring intercept**: sklearn 의 default 는 intercept 의 X regularize — but custom impl 의 watch.
## 🧪 검증 / 중복
- Verified (Hoerl & Kennard 1970, ESL Ch.3, sklearn docs).
- 신뢰도 A.
## 🕓 Changelog
| 날짜 | 변경 |
|---|---|
| 2026-05-08 | Phase 1 |
| 2026-05-10 | Manual cleanup — Ridge regression with closed-form, SVD, kernel, Bayesian variants |