[G1-Sync] Manual knowledge update
This commit is contained in:
@@ -1,64 +1,182 @@
|
||||
---
|
||||
id: wiki-2026-0508-pre-processing-data-for-ai
|
||||
title: Pre processing Data for AI
|
||||
title: Pre-processing Data for AI
|
||||
category: 10_Wiki/Topics
|
||||
status: needs_review
|
||||
status: verified
|
||||
canonical_id: self
|
||||
aliases: [DATA-PRE-001]
|
||||
aliases: [Data Preprocessing, Feature Engineering, Data Cleaning]
|
||||
duplicate_of: none
|
||||
source_trust_level: A
|
||||
confidence_score: 1.0
|
||||
tags: [data-science, ai, machine-learning, preProcessing, data-cleaning, Feature-Engineering, Normalization]
|
||||
confidence_score: 0.9
|
||||
verification_status: applied
|
||||
tags: [data-preprocessing, feature-engineering, ml, sklearn, pipeline]
|
||||
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, pandas, polars
|
||||
---
|
||||
|
||||
# Pre-processing Data for AI (AI를 위한 데이터 전처리)
|
||||
# Pre-processing Data for AI
|
||||
|
||||
## 📌 한 줄 통찰 (The Karpathy Summary)
|
||||
> "데이터의 날것 그대로를 신뢰하지 말고, 지능이 소화하기 가장 편안한 형태로 정제하고 규격화하여 모델의 잠재력을 해방하라" — 분석이나 학습에 적합하지 않은 원시 데이터를 데이터 품질을 높이고 학습 효율을 최적화하기 위해 가공하는 모든 인공지능 워크플로우의 최우선 과정.
|
||||
## 매 한 줄
|
||||
> **"매 raw data를 model-consumable form으로 변환 — clean, scale, encode, impute."**. ML pipeline의 80% 시간이 매 여기에 소요. 매 sklearn `Pipeline` + `ColumnTransformer` 가 표준, modern stack은 polars + sklearn 또는 PyTorch `Dataset` 내 transform.
|
||||
|
||||
## 📖 구조화된 지식 (Synthesized Content)
|
||||
- **추출된 패턴:** "Data Cleansing and Structural [[Alignment|Alignment]]" — 불완전한 기록(Missing value)을 메우고, 극단적인 값(Outlier)을 처리하며, 서로 다른 단위의 숫자들을 동일한 범위로 맞추어(Scaling) 모델이 특정 변수에만 휘둘리지 않게 만드는 패턴.
|
||||
- **주요 작업 단계:**
|
||||
- **Cleaning:** 오타 수정, 결측치 처리(Imputation), 중복 데이터 제거.
|
||||
- **Transformation:** 정규화(Normalization), 표준화(Standardization), 로그 변환.
|
||||
- **Reduction:** 차원 축소(PCA), 특징 선택(Feature Selection).
|
||||
- **Discretization:** 연속형 변수를 범주형으로 변환.
|
||||
- **의의:** 전체 데이터 사이언스 업무의 80% 이상을 차지하는 핵심 노동이자, 모델의 성능 하한선을 결정짓는 가장 실질적인 품질 관리 과정.
|
||||
## 매 핵심
|
||||
|
||||
## ⚠️ 모순 및 업데이트 (Contradictions & Updates)
|
||||
- **과거 데이터와의 충돌:** 사람이 일일이 규칙을 만들어 전처리하던 방식에서, 이제는 전처리 과정 자체를 학습하여 최적화하는 Auto-Preprocessing 기술과 데이터 유효성을 자동으로 검사하는 Data Observability 도구들이 필수적으로 도입되고 있음.
|
||||
- **정책 변화:** Antigravity 프로젝트는 외부 원시 위키 데이터를 시스템으로 가져올 때, 텍스트 내의 불필요한 마크업이나 특수 기호를 제거하고 Karpathy 스타일로 재구성하기 위한 전용 NLP 전처리 엔진을 가동함.
|
||||
### 매 단계
|
||||
1. **Cleaning**: duplicate 제거, type 정정, outlier 처리.
|
||||
2. **Missing imputation**: mean/median/mode, KNN, MICE, model-based.
|
||||
3. **Encoding**: categorical → numeric (one-hot, target, ordinal, embedding).
|
||||
4. **Scaling**: numeric range 정규화 (standard, minmax, robust).
|
||||
5. **Feature engineering**: domain feature, interaction, polynomial, time lag.
|
||||
6. **Splitting**: train/val/test — 매 leak 방지가 핵심.
|
||||
|
||||
## 🔗 지식 연결 (Graph)
|
||||
- [[Normalization-Strategies|Normalization-Strategies]], [[Outlier-Detection-Techniques|Outlier-Detection-Techniques]], [[One-Hot-Encoding|One-Hot-Encoding]], [[Exploratory-Data-Analysis|Exploratory-Data-Analysis]]
|
||||
- **Raw Source:** 10_Wiki/Topics/AI/Pre-processing-Data-for-AI.md
|
||||
### 매 leakage 방지 원칙
|
||||
- Fit transform on **train only**, apply on val/test.
|
||||
- 매 sklearn `Pipeline` 안에 모두 포함 — cross-val 안전.
|
||||
- Time-series는 매 chronological split.
|
||||
|
||||
## 🤖 LLM 활용 힌트 (How to Use This Knowledge)
|
||||
### 매 응용
|
||||
1. Tabular ML (XGBoost / LightGBM / CatBoost) 매 input 준비.
|
||||
2. NLP tokenization + truncation + padding.
|
||||
3. Vision augmentation (flip, crop, mixup, RandAugment).
|
||||
4. Time-series feature lag, rolling stat.
|
||||
|
||||
**언제 이 지식을 쓰는가:**
|
||||
- *(TODO)*
|
||||
## 💻 패턴
|
||||
|
||||
**언제 쓰면 안 되는가:**
|
||||
- *(TODO)*
|
||||
### sklearn Pipeline + ColumnTransformer (canonical)
|
||||
```python
|
||||
import pandas as pd
|
||||
from sklearn.compose import ColumnTransformer
|
||||
from sklearn.pipeline import Pipeline
|
||||
from sklearn.preprocessing import StandardScaler, OneHotEncoder
|
||||
from sklearn.impute import SimpleImputer
|
||||
from sklearn.ensemble import GradientBoostingClassifier
|
||||
|
||||
## 🧪 검증 상태 (Validation)
|
||||
num = ['age', 'income']
|
||||
cat = ['city', 'plan']
|
||||
|
||||
- **정보 상태:** needs_review
|
||||
- **출처 신뢰도:** A
|
||||
- **검토 이유:** *(P-Reinforce Phase 1 자동 정규화. 본문 검증 필요.)*
|
||||
num_pipe = Pipeline([
|
||||
('imp', SimpleImputer(strategy='median')),
|
||||
('sc', StandardScaler()),
|
||||
])
|
||||
cat_pipe = Pipeline([
|
||||
('imp', SimpleImputer(strategy='most_frequent')),
|
||||
('oh', OneHotEncoder(handle_unknown='ignore')),
|
||||
])
|
||||
pre = ColumnTransformer([('num', num_pipe, num), ('cat', cat_pipe, cat)])
|
||||
|
||||
## 🧬 중복 검사 (Duplicate Check)
|
||||
clf = Pipeline([('pre', pre), ('m', GradientBoostingClassifier())])
|
||||
clf.fit(X_train, y_train)
|
||||
```
|
||||
|
||||
- **기존 유사 문서:** *(TODO: 인덱서 클러스터 리포트 참조)*
|
||||
- **처리 방식:** UPDATE (자동 정규화)
|
||||
- **처리 이유:** Phase 1 정규화 — 옛 템플릿/누락 필드 보강.
|
||||
### Train/val/test split (no leak)
|
||||
```python
|
||||
from sklearn.model_selection import train_test_split
|
||||
X_tr, X_te, y_tr, y_te = train_test_split(X, y, test_size=0.2,
|
||||
stratify=y, random_state=42)
|
||||
X_tr, X_val, y_tr, y_val = train_test_split(X_tr, y_tr, test_size=0.2,
|
||||
stratify=y_tr, random_state=42)
|
||||
```
|
||||
|
||||
## 🕓 변경 이력 (Changelog)
|
||||
### Target encoding (high-cardinality categorical)
|
||||
```python
|
||||
from category_encoders import TargetEncoder
|
||||
te = TargetEncoder(cols=['zip_code'])
|
||||
X_train_enc = te.fit_transform(X_train, y_train)
|
||||
X_test_enc = te.transform(X_test)
|
||||
```
|
||||
|
||||
| 날짜 | 변경 내용 | 처리 방식 | 신뢰도 |
|
||||
|------|-----------|-----------|--------|
|
||||
| 2026-05-08 | P-Reinforce Phase 1 정규화 (frontmatter + 헤더 표준화) | UPDATE | A |
|
||||
### Outlier handling (winsorize + RobustScaler)
|
||||
```python
|
||||
from scipy.stats import mstats
|
||||
import numpy as np
|
||||
X['amount'] = mstats.winsorize(X['amount'], limits=[0.01, 0.01])
|
||||
|
||||
from sklearn.preprocessing import RobustScaler
|
||||
X[['amount']] = RobustScaler().fit_transform(X[['amount']])
|
||||
```
|
||||
|
||||
### Time-series lag / rolling features (polars)
|
||||
```python
|
||||
import polars as pl
|
||||
df = (
|
||||
df.sort('ts')
|
||||
.with_columns([
|
||||
pl.col('y').shift(1).alias('y_lag1'),
|
||||
pl.col('y').shift(7).alias('y_lag7'),
|
||||
pl.col('y').rolling_mean(window_size=7).alias('y_ma7'),
|
||||
])
|
||||
)
|
||||
```
|
||||
|
||||
### Image augmentation (torchvision v2)
|
||||
```python
|
||||
from torchvision.transforms import v2
|
||||
import torch
|
||||
train_tf = v2.Compose([
|
||||
v2.RandomResizedCrop(224, antialias=True),
|
||||
v2.RandomHorizontalFlip(),
|
||||
v2.RandAugment(),
|
||||
v2.ToDtype(torch.float32, scale=True),
|
||||
v2.Normalize(mean=[0.485,0.456,0.406], std=[0.229,0.224,0.225]),
|
||||
])
|
||||
```
|
||||
|
||||
### KNN imputer (correlated missing)
|
||||
```python
|
||||
from sklearn.impute import KNNImputer
|
||||
imp = KNNImputer(n_neighbors=5)
|
||||
X_imp = imp.fit_transform(X)
|
||||
```
|
||||
|
||||
### Iterative (MICE) imputer
|
||||
```python
|
||||
from sklearn.experimental import enable_iterative_imputer # noqa
|
||||
from sklearn.impute import IterativeImputer
|
||||
imp = IterativeImputer(max_iter=10, random_state=0)
|
||||
X_imp = imp.fit_transform(X)
|
||||
```
|
||||
|
||||
## 매 결정 기준
|
||||
| 상황 | Approach |
|
||||
|---|---|
|
||||
| Numeric, gaussian-like | StandardScaler |
|
||||
| Numeric with outliers | RobustScaler 또는 winsorize |
|
||||
| Numeric bounded [0,1] 필요 | MinMaxScaler |
|
||||
| Low-cardinality categorical | OneHotEncoder |
|
||||
| High-cardinality categorical | Target encoding 또는 embedding |
|
||||
| Tree-based (XGBoost) | scaling 불필요, encoding은 ordinal/native cat OK |
|
||||
| Time-series | lag/rolling feature, chronological split |
|
||||
| Image | torchvision/timm augmentation |
|
||||
|
||||
**기본값**: tabular는 sklearn Pipeline + ColumnTransformer, vision은 torchvision v2.
|
||||
|
||||
## 🔗 Graph
|
||||
- 부모: [[Machine_Learning]] · [[Data_Engineering]]
|
||||
- 변형: [[Feature_Engineering]] · [[Feature_Scaling]] · [[Encoding_Categorical]]
|
||||
- 응용: [[Tabular_ML]] · [[NLP_Tokenization]] · [[Image_Augmentation]]
|
||||
- Adjacent: [[Data_Cleaning]] · [[Imbalanced_Data]] · [[Cross_Validation]]
|
||||
|
||||
## 🤖 LLM 활용
|
||||
**언제**: tabular ML 매 input prep, time-series feature gen, image/text augmentation pipeline 설계.
|
||||
**언제 X**: 매 modern deep learning에서 raw input → end-to-end (CNN/Transformer가 매 representation 학습) — pretrained 사용 시 normalization만.
|
||||
|
||||
## ❌ 안티패턴
|
||||
- **Fit scaler on full data before split**: 매 leak — val/test 정보가 train scaler에 누출.
|
||||
- **One-hot 1000+ category**: 매 sparse 폭발. Target encoding 또는 embedding.
|
||||
- **Drop all NaN rows**: 매 loss huge. Imputation 또는 missing indicator.
|
||||
- **Standardize tree-based input**: 매 pointless — tree는 scale invariant.
|
||||
- **Same augmentation on val**: 매 train만 augment, val/test deterministic.
|
||||
|
||||
## 🧪 검증 / 중복
|
||||
- Verified (sklearn user guide preprocessing, pandas docs, polars docs, torchvision v2 transforms).
|
||||
- 신뢰도 A.
|
||||
|
||||
## 🕓 Changelog
|
||||
| 날짜 | 변경 |
|
||||
|---|---|
|
||||
| 2026-05-08 | Phase 1 |
|
||||
| 2026-05-10 | Manual cleanup — preprocessing stages + sklearn Pipeline + leakage rules |
|
||||
|
||||
Reference in New Issue
Block a user