[G1-Sync] Manual knowledge update
This commit is contained in:
@@ -1,62 +1,146 @@
|
||||
---
|
||||
id: wiki-2026-0508-kernel-density-estimation-kde
|
||||
title: Kernel Density Estimation KDE
|
||||
title: Kernel Density Estimation (KDE)
|
||||
category: 10_Wiki/Topics
|
||||
status: needs_review
|
||||
status: verified
|
||||
canonical_id: self
|
||||
aliases: [MATH-KDE-001]
|
||||
aliases: [KDE, Parzen Window, Density Estimation]
|
||||
duplicate_of: none
|
||||
source_trust_level: A
|
||||
confidence_score: 1.0
|
||||
tags: ["Statistics|[Statistics", math, kde, density-estimation, data-visualization, probability]
|
||||
confidence_score: 0.9
|
||||
verification_status: applied
|
||||
tags: [statistics, non-parametric, density-estimation, kernel]
|
||||
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: scipy, scikit-learn, KDEpy
|
||||
---
|
||||
|
||||
# Kernel Density Estimation (KDE, 커널 밀도 추정)
|
||||
# Kernel Density Estimation (KDE)
|
||||
|
||||
## 📌 한 줄 통찰 (The Karpathy Summary)
|
||||
> "데이터라는 개별 점들에 부드러운 산 모양의 확률을 씌워, 전체의 흐름을 보여주는 부드러운 능선을 그려라" — 유한한 표본 데이터를 바탕으로 모집단의 확률 밀도 함수(PDF)를 부드럽게 추정하여 데이터의 분포 특성을 파악하는 기계학습 및 통계학의 핵심 도구.
|
||||
## 매 한 줄
|
||||
> **"매 histogram 의 smooth 한 generalization"**. KDE 는 non-parametric density estimator 로, 매 sample point 에 kernel function 을 placing 하고 sum 하여 continuous PDF 추정. Parzen (1962) 와 Rosenblatt (1956) 이 정립했으며, 2026 modern stats/ML 에서 anomaly detection, generative sampling, visualization 에 사용.
|
||||
|
||||
## 📖 구조화된 지식 (Synthesized Content)
|
||||
- **추출된 패턴:** "Smoothing and Summation" — 각 데이터 포인트 위치에 커널 함수(주로 가우시안)를 배치하고, 이들을 모두 합산하여 데이터가 밀집된 곳은 높게, 희소한 곳은 낮게 표현하는 공간적 밀도 추론 패턴.
|
||||
- **주요 구성 요소:**
|
||||
- **Kernel Function:** 데이터의 영향력을 주변으로 퍼뜨리는 함수 형태.
|
||||
- **Bandwidth ($h$):** 함수의 넓이(매끄러움)를 조절하는 파라미터. $h$가 너무 작으면 과적합([[Overfitting|Overfitting]]), 너무 크면 분포가 뭉개짐(Underfitting).
|
||||
- **의의:** 히스토그램과 달리 빈(Bin)의 크기나 시작점에 민감하지 않으며, 데이터의 실제 분포 형태를 훨씬 더 정확하게 반영할 수 있음.
|
||||
## 매 핵심
|
||||
|
||||
## ⚠️ 모순 및 업데이트 (Contradictions & Updates)
|
||||
- **과거 데이터와의 충돌:** 단순한 시각화 도구로 여겨졌으나, 최근에는 이상치 탐지(Anomaly Detection)나 생성 모델(Generative Models)의 기초 이론으로 중요성이 다시 부각됨.
|
||||
- **정책 변화:** Antigravity 프로젝트는 에이전트의 응답 시간 분포를 분석하여 병목 구간을 시각화할 때, 히스토그램 대신 KDE 곡선을 사용하여 통계적 왜곡을 방지함.
|
||||
### 매 수식
|
||||
- $\hat{f}_h(x) = \frac{1}{nh}\sum_{i=1}^n K\left(\frac{x - x_i}{h}\right)$
|
||||
- $K$ = kernel (Gaussian, Epanechnikov, …)
|
||||
- $h$ = bandwidth (smoothing parameter)
|
||||
- multi-D: $\hat{f}_H(x) = \frac{1}{n|H|^{1/2}}\sum K(H^{-1/2}(x-x_i))$
|
||||
|
||||
## 🔗 지식 연결 (Graph)
|
||||
- Probability-Theory, [[Exploratory-Data-Analysis|Exploratory-Data-Analysis]], [[Anomaly-Detection|Anomaly-Detection]]-Foundations, [[Supervised-Learning-Foundations|Supervised-Learning-Foundations]]
|
||||
- **Raw Source:** 10_Wiki/Topics/AI/Kernel-Density-Estimation-KDE.md
|
||||
### 매 Bandwidth selection
|
||||
- Silverman's rule: $h = 1.06 \hat{\sigma} n^{-1/5}$
|
||||
- Scott's rule: $h = n^{-1/(d+4)}$
|
||||
- cross-validation (likelihood)
|
||||
- plug-in estimators (Sheather-Jones)
|
||||
|
||||
## 🤖 LLM 활용 힌트 (How to Use This Knowledge)
|
||||
### 매 응용
|
||||
1. EDA visualization (seaborn `kdeplot`).
|
||||
2. Anomaly detection (low-density = outlier).
|
||||
3. Mode finding (mean-shift).
|
||||
4. Bayesian non-parametric prior.
|
||||
5. Generative sampling (smoothed bootstrap).
|
||||
|
||||
**언제 이 지식을 쓰는가:**
|
||||
- *(TODO)*
|
||||
## 💻 패턴
|
||||
|
||||
**언제 쓰면 안 되는가:**
|
||||
- *(TODO)*
|
||||
### scipy KDE
|
||||
```python
|
||||
from scipy.stats import gaussian_kde
|
||||
import numpy as np
|
||||
|
||||
## 🧪 검증 상태 (Validation)
|
||||
x = np.random.normal(0, 1, 1000)
|
||||
kde = gaussian_kde(x, bw_method="silverman")
|
||||
|
||||
- **정보 상태:** needs_review
|
||||
- **출처 신뢰도:** A
|
||||
- **검토 이유:** *(P-Reinforce Phase 1 자동 정규화. 본문 검증 필요.)*
|
||||
xs = np.linspace(-4, 4, 200)
|
||||
density = kde(xs)
|
||||
```
|
||||
|
||||
## 🧬 중복 검사 (Duplicate Check)
|
||||
### sklearn KernelDensity
|
||||
```python
|
||||
from sklearn.neighbors import KernelDensity
|
||||
import numpy as np
|
||||
|
||||
- **기존 유사 문서:** *(TODO: 인덱서 클러스터 리포트 참조)*
|
||||
- **처리 방식:** UPDATE (자동 정규화)
|
||||
- **처리 이유:** Phase 1 정규화 — 옛 템플릿/누락 필드 보강.
|
||||
X = np.random.randn(1000, 2)
|
||||
kde = KernelDensity(kernel="gaussian", bandwidth=0.3).fit(X)
|
||||
log_dens = kde.score_samples(X) # log-density at each point
|
||||
|
||||
## 🕓 변경 이력 (Changelog)
|
||||
# anomaly: lowest 1% as outliers
|
||||
threshold = np.quantile(log_dens, 0.01)
|
||||
outliers = X[log_dens < threshold]
|
||||
```
|
||||
|
||||
| 날짜 | 변경 내용 | 처리 방식 | 신뢰도 |
|
||||
|------|-----------|-----------|--------|
|
||||
| 2026-05-08 | P-Reinforce Phase 1 정규화 (frontmatter + 헤더 표준화) | UPDATE | A |
|
||||
### Bandwidth via cross-validation
|
||||
```python
|
||||
from sklearn.model_selection import GridSearchCV
|
||||
|
||||
params = {"bandwidth": np.logspace(-1, 1, 20)}
|
||||
grid = GridSearchCV(KernelDensity(), params, cv=5)
|
||||
grid.fit(X)
|
||||
print(grid.best_params_)
|
||||
```
|
||||
|
||||
### KDEpy fast FFT-based KDE
|
||||
```python
|
||||
from KDEpy import FFTKDE
|
||||
x_grid, y = FFTKDE(kernel="gaussian", bw="silverman").fit(x).evaluate()
|
||||
# O(n + m log m) instead of O(n*m)
|
||||
```
|
||||
|
||||
### Adaptive bandwidth
|
||||
```python
|
||||
def adaptive_kde(x, x_eval, k=10):
|
||||
from scipy.spatial import cKDTree
|
||||
tree = cKDTree(x[:, None])
|
||||
dists, _ = tree.query(x[:, None], k=k+1)
|
||||
h_local = dists[:, -1] # k-NN distance per point
|
||||
out = np.zeros_like(x_eval)
|
||||
for xi, hi in zip(x, h_local):
|
||||
out += np.exp(-0.5*((x_eval - xi)/hi)**2) / hi
|
||||
return out / (len(x) * np.sqrt(2*np.pi))
|
||||
```
|
||||
|
||||
### Visualization
|
||||
```python
|
||||
import seaborn as sns
|
||||
sns.kdeplot(data=df, x="feature", hue="class", fill=True, common_norm=False)
|
||||
```
|
||||
|
||||
## 매 결정 기준
|
||||
| 상황 | Method |
|
||||
|---|---|
|
||||
| 1D, small n | scipy gaussian_kde |
|
||||
| high-D, n>10⁴ | FFTKDE |
|
||||
| streaming | online KDE (Heinz 2008) |
|
||||
| boundaries | reflection / log-transform |
|
||||
| heavy-tail | adaptive bandwidth |
|
||||
|
||||
**기본값**: Silverman + Gaussian kernel, then validate.
|
||||
|
||||
## 🔗 Graph
|
||||
- 부모: [[Non-Parametric-Statistics]] · [[Density-Estimation]]
|
||||
- 변형: [[Histogram]] · [[Mean-Shift]] · [[Mixture-Models]]
|
||||
- 응용: [[Anomaly-Detection]] · [[Visualization]]
|
||||
- Adjacent: [[Bandwidth-Selection]] · [[Kernel-Methods]]
|
||||
|
||||
## 🤖 LLM 활용
|
||||
**언제**: small/mid n, distribution shape 알 수 없을 때.
|
||||
**언제 X**: very high-D (curse of dimensionality), n < 30.
|
||||
|
||||
## ❌ 안티패턴
|
||||
- **Default bandwidth blind use**: Silverman 은 Gaussian 가정 — bimodal 에 over-smooth.
|
||||
- **Boundary bias 무시**: support [0, ∞) 인데 Gaussian kernel 사용 → leak 발생.
|
||||
- **High-D KDE**: d > 6 에서는 거의 useless — vine copula 또는 normalizing flow 사용.
|
||||
- **Sample size 무시**: n < 50 KDE 결과는 거의 noise.
|
||||
|
||||
## 🧪 검증 / 중복
|
||||
- Verified (Silverman 1986 textbook, Wand & Jones 1995, Chen 2017 review).
|
||||
- 신뢰도 A.
|
||||
|
||||
## 🕓 Changelog
|
||||
| 날짜 | 변경 |
|
||||
|---|---|
|
||||
| 2026-05-08 | Phase 1 |
|
||||
| 2026-05-10 | Manual cleanup — KDE math, bandwidth selection, scipy/sklearn/KDEpy |
|
||||
|
||||
Reference in New Issue
Block a user