docs(10_Wiki): 위키 전체 재구성 — Topic_* 폴더를 4개 카테고리로 통합 + 대규모 중복 제거
Topic_Agent/Topic_Blog/Topics/Topics_Biz/Topics_Meeting/Topics_Rag의 마크다운 지식 문서를 Topic_General/Topic_Programming/Topic_Graphic/Topic_Business 4개 카테고리로 재분류. - 중복 제거: frontmatter의 status:duplicate/merged + duplicate_of/redirect_to 필드로 자기 자신을 중복으로 선언한 리다이렉트 stub 1032개 제거, 완전 동일 내용 파일 472개 제거, 동일 파일명·다른 내용 충돌 시 더 큰(완전한) 버전만 유지(162개 제거) — 총 1639개 중복 제거. - 분류: 폴더 단위로 명확한 항목(AI_and_ML/Coding/Architecture 등 → Programming, Comfyui/Visual_Effects → Graphic, Topics_Biz/Topics_Meeting/사업 등 → Business, Poetic_Blog_Writing/창의성/Game_Design 등 → General)은 폴더 우선순위로, 나머지 혼재 폴더(Topic_Agent/Topic_Blog/Topics 루트/Thinking & Reasoning/Other/UI_UX_Assets)는 title/tags 키워드 스코어링으로 파일 단위 분류(불명확한 경우 General로 폴백). 원본 폴더명은 "From_*" 서브폴더로 보존해 추적 가능성 유지. - 최종 배치: Programming 2784 / General 1608 / Graphic 285 / Business 249 = 4926개 문서. - 에이전트 운영 상태(.astra/.agent/.obsidian/sessions/memory/_company/docs/lessons/_shared/src)는 지식 콘텐츠가 아니므로 재분류 대상에서 제외하고 원위치 유지. - Topics/Topic_email(상위 보호 폴더 Topic_email과 파일명 100% 중복) 삭제 — 보호 폴더 자체는 미변경. - 완전히 비게 된 Topic_Agent/Topic_Blog/Topics_Biz/Topics_Rag 폴더 제거.
This commit is contained in:
@@ -0,0 +1,151 @@
|
||||
---
|
||||
id: wiki-2026-0508-normalization
|
||||
title: Normalization
|
||||
category: 10_Wiki/Topics
|
||||
status: verified
|
||||
canonical_id: self
|
||||
aliases: [Data Normalization, Feature Scaling, Standardization, BatchNorm, LayerNorm]
|
||||
duplicate_of: none
|
||||
source_trust_level: A
|
||||
confidence_score: 0.95
|
||||
verification_status: applied
|
||||
tags: [normalization, scaling, batchnorm, layernorm, preprocessing]
|
||||
raw_sources: []
|
||||
last_reinforced: 2026-05-10
|
||||
github_commit: pending
|
||||
tech_stack: { language: Python, framework: scikit-learn/PyTorch }
|
||||
---
|
||||
|
||||
## 한 줄
|
||||
입력 피처와 신경망 내부 활성화의 스케일/분포를 안정화해 학습 수렴, 일반화, 수치 안정성을 개선한다.
|
||||
|
||||
## 핵심
|
||||
- **데이터 정규화**:
|
||||
- **z-score (StandardScaler)**: $(x-\mu)/\sigma$ — 정규분포 가정 시 표준.
|
||||
- **min-max**: $[0,1]$ 또는 $[-1,1]$ — bounded 범위 필요 시 (이미지 픽셀).
|
||||
- **robust**: median/IQR — 이상치 강건.
|
||||
- **log/Box-Cox**: heavy-tail/skew 분포에 사용.
|
||||
- **레이어 정규화**:
|
||||
- **BatchNorm**: 배치 차원 통계, CNN 표준.
|
||||
- **LayerNorm**: 피처 차원 통계, Transformer 표준.
|
||||
- **GroupNorm**: 작은 배치 (객체 검출).
|
||||
- **RMSNorm**: LayerNorm 단순화, LLaMA 등 LLM에서 표준.
|
||||
- **fit은 train에만**, test에는 transform.
|
||||
- **Tree 모델 (XGBoost/LightGBM)은 정규화 불필요**.
|
||||
|
||||
## 💻 패턴
|
||||
|
||||
```python
|
||||
# 1) sklearn StandardScaler — train fit, test transform
|
||||
from sklearn.preprocessing import StandardScaler, MinMaxScaler, RobustScaler
|
||||
sc = StandardScaler().fit(X_train)
|
||||
X_train_s, X_test_s = sc.transform(X_train), sc.transform(X_test)
|
||||
# 절대 X_test로 fit하지 말 것 (data leakage)
|
||||
```
|
||||
|
||||
```python
|
||||
# 2) ColumnTransformer — 컬럼별 다른 스케일러
|
||||
from sklearn.compose import ColumnTransformer
|
||||
pre = ColumnTransformer([
|
||||
("std", StandardScaler(), ["age", "income"]),
|
||||
("mm", MinMaxScaler(), ["score"]),
|
||||
("rob", RobustScaler(), ["with_outlier"]),
|
||||
], remainder="passthrough")
|
||||
```
|
||||
|
||||
```python
|
||||
# 3) PyTorch BatchNorm / LayerNorm / GroupNorm
|
||||
import torch.nn as nn
|
||||
bn = nn.BatchNorm2d(num_features=64) # CNN
|
||||
ln = nn.LayerNorm(normalized_shape=768) # Transformer
|
||||
gn = nn.GroupNorm(num_groups=32, num_channels=64) # detection
|
||||
```
|
||||
|
||||
```python
|
||||
# 4) RMSNorm (LLaMA 스타일)
|
||||
import torch
|
||||
class RMSNorm(torch.nn.Module):
|
||||
def __init__(self, dim, eps=1e-6):
|
||||
super().__init__()
|
||||
self.weight = torch.nn.Parameter(torch.ones(dim))
|
||||
self.eps = eps
|
||||
def forward(self, x):
|
||||
rms = x.pow(2).mean(-1, keepdim=True).add(self.eps).rsqrt()
|
||||
return x * rms * self.weight
|
||||
```
|
||||
|
||||
```python
|
||||
# 5) 이미지 정규화 (ImageNet 통계)
|
||||
from torchvision import transforms
|
||||
T = transforms.Compose([
|
||||
transforms.Resize(256), transforms.CenterCrop(224),
|
||||
transforms.ToTensor(),
|
||||
transforms.Normalize(mean=[0.485, 0.456, 0.406], std=[0.229, 0.224, 0.225]),
|
||||
])
|
||||
```
|
||||
|
||||
```python
|
||||
# 6) 시계열 — per-series z-score (rolling, leakage 회피)
|
||||
import numpy as np
|
||||
def rolling_zscore(x, window=60):
|
||||
out = np.full_like(x, np.nan, dtype=float)
|
||||
for i in range(window, len(x)):
|
||||
w = x[i - window:i]
|
||||
out[i] = (x[i] - w.mean()) / (w.std() + 1e-8)
|
||||
return out
|
||||
```
|
||||
|
||||
```python
|
||||
# 7) 로그 변환 (heavy-tail target)
|
||||
import numpy as np
|
||||
y_log = np.log1p(y_train)
|
||||
# 학습 후 예측은 expm1로 역변환
|
||||
y_pred = np.expm1(model.predict(X_test))
|
||||
```
|
||||
|
||||
```python
|
||||
# 8) Pipeline에 스케일러 포함 (CV에서 leakage 방지)
|
||||
from sklearn.pipeline import Pipeline
|
||||
from sklearn.linear_model import Ridge
|
||||
from sklearn.model_selection import cross_val_score
|
||||
pipe = Pipeline([("sc", StandardScaler()), ("est", Ridge(alpha=1.0))])
|
||||
cross_val_score(pipe, X, y, cv=5, scoring="r2")
|
||||
```
|
||||
|
||||
## 결정 기준
|
||||
|
||||
| 데이터/모델 | 추천 |
|
||||
|---|---|
|
||||
| 일반 tabular + 선형/SVM/NN | StandardScaler |
|
||||
| bounded 입력 필요 (이미지/그라디언트 부스팅 X) | MinMax |
|
||||
| 이상치 많음 | RobustScaler |
|
||||
| heavy-tail target | log1p |
|
||||
| CNN | BatchNorm |
|
||||
| Transformer | LayerNorm/RMSNorm |
|
||||
| 작은 배치 (detection) | GroupNorm |
|
||||
| 트리 모델 (XGBoost/LGBM/RF) | 정규화 불필요 |
|
||||
|
||||
## 🔗 Graph
|
||||
- 부모: [[Feature Engineering]], [[Deep Learning]]
|
||||
- 인접: [[Standardization]], [[Layer Normalization]]
|
||||
|
||||
## 🤖 LLM 활용
|
||||
- 피처 분포 (skew/kurtosis) → 스케일러 선택 추천.
|
||||
- 학습 불안정 디버그 (loss NaN) → norm layer 진단.
|
||||
- pipeline 코드 생성 (column 단위).
|
||||
|
||||
## ❌ 안티패턴
|
||||
- test로 fit 또는 전체 데이터로 fit (leakage).
|
||||
- 트리 모델에 굳이 정규화 적용.
|
||||
- BatchNorm을 RNN/Transformer에 사용.
|
||||
- 이미지에서 0-255 raw 값을 그대로 NN에 입력.
|
||||
- 시계열에서 미래 데이터 포함한 글로벌 통계 사용.
|
||||
|
||||
## 🧪 검증
|
||||
- train/test 분포 차이: KS test, PSI.
|
||||
- 정규화 후 mean≈0, std≈1 (z-score) 확인.
|
||||
- 학습 curve가 정규화 적용/미적용에서 안정성 비교.
|
||||
|
||||
## 🕓 Changelog
|
||||
- 2026-05-08 Phase 1 자동 생성
|
||||
- 2026-05-10 Manual cleanup — house style 적용
|
||||
Reference in New Issue
Block a user