[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,200 @@
id: wiki-2026-0508-kernel-methods-and-svms
title: Kernel Methods and SVMs
category: 10_Wiki/Topics
status: needs_review
status: verified
canonical_id: self
aliases: [ML-SVM-001]
aliases: [SVM, kernel methods, RBF kernel, kernel trick, support vector machine]
duplicate_of: none
source_trust_level: A
confidence_score: 1.0
tags: [machine-learning, svm, kernel-methods, Optimization, classification, kernel-trick]
confidence_score: 0.95
verification_status: applied
tags: [machine-learning, svm, kernel, classical-ml, scikit-learn]
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 / libsvm
---
# Kernel Methods and SVMs (커널 메서드와 SVM)
# Kernel Methods and SVMs
## 📌 한 줄 통찰 (The Karpathy Summary)
> "데이터를 더 높은 차원으로 끌어올려 복잡하게 얽힌 실타래를 한 칼에 베어버리는 최적의 경계선을 찾아라" — 데이터를 고차원 공간으로 매핑하여 비선형적인 관계를 선형적으로 분리 가능하게 만드는 '커널 트릭'과, 두 클래스 사이의 거리(Margin)를 최대화하는 'SVM'의 결합.
## 한 줄
> **"매 implicit feature space 의 의 의 의 inner product"**. 매 kernel trick — 매 high-dim transform 의 explicit X. 매 SVM (Vapnik) 의 의 의 dominant pre-DL. 매 modern: 매 small data 의 still 매 strong baseline. 매 GP 의 covariance 도 kernel.
## 📖 구조화된 지식 (Synthesized Content)
- **추출된 패턴:** "Max-Margin Hyperplane" — 단순히 클래스를 나누는 것을 넘어, 양측 데이터([[Support|Support]] Vectors)로부터 가장 멀리 떨어진 최적의 안전거리(Margin)를 확보하여 모델의 일반화 능력을 극대화하는 최적화 패턴.
- **핵심 개념:**
- **Support Vectors:** 결정 경계를 결정하는 가장 가까운 데이터 포인트들.
- **Kernel Trick:** 실제로 차원을 높이지 않고도 고차원 내적 연산 효과를 내는 수학적 기법 (RBF, Polynomial Kernel 등).
- **Slack Variables:** 일부 오차를 허용하여 노이즈에 강건하게 만드는 기법 (Soft Margin).
- **의의:** 수학적으로 명확한 해(Global Optimum)를 보장하며, 데이터가 적은 상황에서도 딥러닝에 필적하는 강력한 성능을 발휘함.
## 매 핵심
## ⚠️ 모순 및 업데이트 (Contradictions & Updates)
- **과거 데이터와의 충돌:** 모든 문제를 해결할 만능 알고리즘으로 추앙받았으나, 데이터 규모가 커질수록 연산량이 기하급수적으로 늘어나는 한계로 인해 대규모 데이터셋에서는 딥러닝에 자리를 내어줌.
- **정책 변화:** Antigravity 프로젝트는 실시간 이상 징후 탐지 시, 데이터셋이 작고 경계가 명확해야 하는 특정 보안 도메인에서 One-class SVM을 적극적으로 활용함.
### 매 SVM
- **Hard-margin**: 매 separable.
- **Soft-margin** (slack): 매 misclassify allow.
- **Dual form**: 매 의 의 의 의 kernel trick.
## 🔗 지식 연결 (Graph)
- [[Supervised-Learning-Foundations|Supervised-Learning-Foundations]], [[Inner-Product-Spaces|Inner-Product-Spaces]], [[Dimensionality-Reduction|Dimensionality-Reduction]], [[Global-vs-Local-Optima|Global-vs-Local-Optima]]
- **Raw Source:** 10_Wiki/Topics/AI/Kernel-Methods-and-SVMs.md
### 매 kernel
- **Linear**: K(x, y) = x·y.
- **Polynomial**: (γ x·y + r)^d.
- **RBF / Gaussian**: exp(-γ ||x-y||²).
- **Sigmoid**: tanh(γ x·y + r).
- **String, Graph kernels** (specialized).
## 🤖 LLM 활용 힌트 (How to Use This Knowledge)
### 매 응용
1. **Small-data classification**.
2. **Text classification** (TF-IDF + linear SVM 의 historically strong).
3. **Anomaly** (1-class SVM).
4. **Regression** (SVR).
5. **Bioinformatics**.
**언제 이 지식을 쓰는가:**
- *(TODO)*
## 💻 패턴
**언제 쓰면 안 되는가:**
- *(TODO)*
### Basic SVM (sklearn)
```python
from sklearn.svm import SVC
clf = SVC(kernel='rbf', C=1.0, gamma='scale').fit(X_train, y_train)
preds = clf.predict(X_test)
```
## 🧪 검증 상태 (Validation)
### Linear SVM (large-scale)
```python
from sklearn.svm import LinearSVC
clf = LinearSVC(C=1.0).fit(X, y) # 매 fast for large N
```
- **정보 상태:** needs_review
- **출처 신뢰도:** A
- **검토 이유:** *(P-Reinforce Phase 1 자동 정규화. 본문 검증 필요.)*
### CV-tune C and gamma
```python
from sklearn.model_selection import GridSearchCV
params = {'C': [0.1, 1, 10, 100], 'gamma': [0.001, 0.01, 0.1, 1]}
grid = GridSearchCV(SVC(kernel='rbf'), params, cv=5)
grid.fit(X, y)
```
## 🧬 중복 검사 (Duplicate Check)
### SVR (regression)
```python
from sklearn.svm import SVR
model = SVR(kernel='rbf', C=1.0, epsilon=0.1).fit(X, y)
```
- **기존 유사 문서:** *(TODO: 인덱서 클러스터 리포트 참조)*
- **처리 방식:** UPDATE (자동 정규화)
- **처리 이유:** Phase 1 정규화 — 옛 템플릿/누락 필드 보강.
### One-class SVM (anomaly)
```python
from sklearn.svm import OneClassSVM
clf = OneClassSVM(gamma='auto').fit(X_normal)
anomalies = clf.predict(X_test) == -1
```
## 🕓 변경 이력 (Changelog)
### Custom kernel
```python
def my_kernel(X, Y):
return X @ Y.T + 1 # 매 example
| 날짜 | 변경 내용 | 처리 방식 | 신뢰도 |
|------|-----------|-----------|--------|
| 2026-05-08 | P-Reinforce Phase 1 정규화 (frontmatter + 헤더 표준화) | UPDATE | A |
clf = SVC(kernel=my_kernel).fit(X, y)
```
### Kernel trick (manual feature mapping vs)
```python
import numpy as np
def rbf_kernel(x, y, gamma=1.0):
return np.exp(-gamma * np.linalg.norm(x - y) ** 2)
def poly_kernel(x, y, d=2, gamma=1.0, r=0):
return (gamma * x @ y + r) ** d
```
### TF-IDF + linear SVM (text classic)
```python
from sklearn.feature_extraction.text import TfidfVectorizer
from sklearn.pipeline import Pipeline
pipe = Pipeline([('tfidf', TfidfVectorizer(max_features=20000)), ('svm', LinearSVC(C=1.0))])
pipe.fit(train_texts, train_labels)
```
### Multi-class (one-vs-rest)
```python
from sklearn.multiclass import OneVsRestClassifier
clf = OneVsRestClassifier(SVC()).fit(X, y)
```
### Calibrated probabilities
```python
from sklearn.calibration import CalibratedClassifierCV
clf = CalibratedClassifierCV(SVC(kernel='rbf'), cv=5).fit(X, y)
probs = clf.predict_proba(X_test)
```
### Kernel approximation (large data)
```python
from sklearn.kernel_approximation import RBFSampler
rbf_feature = RBFSampler(gamma=1, n_components=100, random_state=0)
X_features = rbf_feature.fit_transform(X)
# 매 매 linear SVM 의 의 OK
clf = LinearSVC().fit(X_features, y)
```
### String kernel (text)
```python
from sklearn.feature_extraction.text import CountVectorizer
def n_gram_kernel(X, Y, n=3):
vec = CountVectorizer(analyzer='char', ngram_range=(n, n))
Xv = vec.fit_transform(X).toarray()
Yv = vec.transform(Y).toarray()
return Xv @ Yv.T
```
### Graph kernel (Weisfeiler-Lehman)
```python
from grakel.kernels import WeisfeilerLehman
from grakel import GraphKernel
gk = GraphKernel(kernel='weisfeiler_lehman', n_iter=5)
K_train = gk.fit_transform(graphs_train)
K_test = gk.transform(graphs_test)
clf = SVC(kernel='precomputed').fit(K_train, y_train)
```
### Plot decision boundary (2D)
```python
import matplotlib.pyplot as plt
def plot_boundary(clf, X, y):
h = 0.02
x_min, x_max = X[:, 0].min() - 1, X[:, 0].max() + 1
y_min, y_max = X[:, 1].min() - 1, X[:, 1].max() + 1
xx, yy = np.meshgrid(np.arange(x_min, x_max, h), np.arange(y_min, y_max, h))
Z = clf.predict(np.c_[xx.ravel(), yy.ravel()]).reshape(xx.shape)
plt.contourf(xx, yy, Z, alpha=0.3)
plt.scatter(X[:, 0], X[:, 1], c=y)
```
## 매 결정 기준
| 상황 | Approach |
|---|---|
| Small data | RBF SVM |
| High-dim text | Linear SVM (TF-IDF) |
| Anomaly | One-class SVM |
| Graph data | WL graph kernel |
| Large-scale | Linear SVM or kernel approx |
| Modern DL data | Use DL instead |
**기본값**: 매 small N + tabular = RBF SVM. 매 text = Linear + TF-IDF. 매 large = kernel approximation. 매 modern era — DL win on most.
## 🔗 Graph
- 부모: [[Machine-Learning]] · [[Classical-ML]]
- 변형: [[SVM]] · [[SVR]] · [[One-Class-SVM]]
- 응용: [[Text-Classification]] · [[Anomaly-Detection]]
- Adjacent: [[Gaussian-Processes]] · [[Neural-Tangent-Kernel]]
## 🤖 LLM 활용
**언제**: 매 small data. 매 baseline. 매 anomaly.
**언제 X**: 매 large data (DL win).
## ❌ 안티패턴
- **No scaling**: 매 RBF 의 의 의 critical.
- **RBF on huge N**: 매 O(N²) 의 fail.
- **Default C / gamma**: 매 always tune.
- **No probability calibration**: 매 SVM 의 raw decision 의 not probability.
## 🧪 검증 / 중복
- Verified (Vapnik 1995, Schölkopf, scikit-learn docs).
- 신뢰도 A.
## 🕓 Changelog
| 날짜 | 변경 |
|---|---|
| 2026-05-08 | Phase 1 |
| 2026-05-10 | Manual cleanup — kernels + 매 SVM / SVR / OCSVM / approx / graph code |