Skip to content

Machine Learning 치트시트

머신러닝 개념, 알고리즘, Python 구현입니다.

01

시작하기

머신러닝이란?

머신러닝은 손으로 쓴 규칙을 따르는 대신 데이터에서 일반화하는 시스템을 만듭니다. 세 가지 패러다임(지도, 비지도, 강화)이 대부분의 실제 문제를 커버합니다. 구조화된 워크플로우 — 특히 깨끗한 테스트 셋을 따로 두는 것 — 을 따르면 평가에 과적합하는 치명적 죄를 막습니다.

machine-learning
# Machine Learning: systems that learn patterns from data
# instead of being explicitly programmed.

# Three main paradigms:
# - Supervised:    learn f: X -> y from labeled (X, y) pairs
# - Unsupervised:  find structure in unlabeled X
# - Reinforcement: learn actions that maximize reward via trial-and-error

# Typical workflow:
# 1. Define problem & collect data
# 2. Preprocess & feature engineering
# 3. Split train / validation / test
# 4. Train model, tune hyperparameters
# 5. Evaluate on test set
# 6. Deploy & monitor

핵심 라이브러리

scikit-learn이 표 형식/클래식 ML의 주력입니다 — 모든 알고리즘에서 일관된 fit/predict/transform API. 데이터 정제는 NumPy와 Pandas가, 시각화는 Matplotlib/Seaborn이 담당합니다. 딥러닝은 PyTorch(연구 친화적)나 TensorFlow/Keras(프로덕션 친화적) 중 고르세요 — 둘 다 같은 영역을 커버합니다.

machine-learning
# The standard ML stack in Python
import numpy as np          # numerical arrays
import pandas as pd         # tabular data
import matplotlib.pyplot as plt  # plotting
import seaborn as sns       # statistical plots

# scikit-learn: classical ML (trees, SVM, linear models, preprocessing)
from sklearn.model_selection import train_test_split
from sklearn.ensemble import RandomForestClassifier
from sklearn.metrics import accuracy_score

# Deep learning (pick one):
import torch                # PyTorch
# import tensorflow as tf   # TensorFlow/Keras

# Install:
# pip install numpy pandas matplotlib seaborn scikit-learn torch

학습 / 검증 / 테스트 분할

최종 평가 전까지는 테스트 셋을 절대 건드리지 마세요 — 튜닝에 쓰면 정보가 새어 나가 보고된 지표가 부풀려집니다. stratify=y가 클래스 균형을 유지하며, 불균형 분류에 결정적입니다. random_state가 분할을 재현 가능하게 만듭니다. 작은 데이터셋에는 고정 검증 셋 대신 k-fold CV를 쓰세요.

machine-learning
from sklearn.model_selection import train_test_split

X_train, X_test, y_train, y_test = train_test_split(
    X, y,
    test_size=0.2,      # 20% held out for test
    random_state=42,    # reproducibility
    stratify=y,         # keep class proportions (classification only)
)

# For a third validation set:
X_train, X_temp, y_train, y_temp = train_test_split(
    X, y, test_size=0.4, stratify=y, random_state=42)
X_val, X_test, y_val, y_test = train_test_split(
    X_temp, y_temp, test_size=0.5, stratify=y_temp, random_state=42)
# Now: 60% train, 20% val, 20% test

첫 모델 (Iris)

Iris 데이터셋은 ML의 'Hello World'입니다 — 150개 꽃 샘플, 4개 특성, 3개 클래스. 이 스니펫이 정석적인 sklearn 패턴을 보여줍니다: 데이터 로드 → 분할 → 모델 인스턴스화 → fit → predict → 평가. classification_report가 클래스별 정밀도/재현율/F1을 주며, 불균형 문제에서 정확도 하나보다 훨씬 정보적입니다.

machine-learning
from sklearn.datasets import load_iris
from sklearn.model_selection import train_test_split
from sklearn.ensemble import RandomForestClassifier
from sklearn.metrics import accuracy_score, classification_report

iris = load_iris()
X, y = iris.data, iris.target

X_train, X_test, y_train, y_test = train_test_split(
    X, y, test_size=0.2, stratify=y, random_state=42)

model = RandomForestClassifier(n_estimators=100, random_state=42)
model.fit(X_train, y_train)
y_pred = model.predict(X_test)

print("Accuracy:", accuracy_score(y_test, y_pred))
print(classification_report(y_test, y_pred, target_names=iris.target_names))

재현성

numpy, random, 자신의 DL 프레임워크에 시드를 설정하면 가중치 초기화와 셔플링이 재현 가능해집니다. 확률적인 모든 sklearn 추정기에는 random_state를 전달하세요. 완전한 결정론성(특히 GPU)에는 결정론적 알고리즘과 env flag도 필요합니다 — '맞아야' 하는데 안 맞는 결과를 디버깅할 때 유용합니다.

machine-learning
import numpy as np
import random
import torch

SEED = 42
np.random.seed(SEED)
random.seed(SEED)
torch.manual_seed(SEED)
if torch.cuda.is_available():
    torch.cuda.manual_seed_all(SEED)

# For sklearn, pass random_state to each estimator:
# RandomForestClassifier(random_state=SEED)

# Force deterministic operations (slower but fully reproducible):
torch.use_deterministic_algorithms(True)

# Optional: pin GPU non-determinism
import os
os.environ["CUBLAS_WORKSPACE_CONFIG"] = ":4096:8"
02

데이터 전처리

결측값 처리

전체 데이터셋에 imputer를 fit하면 테스트 통계가 학습에 새어 나갑니다 — 항상 train에만 fit하세요. Median이 mean보다 이상치에 강합니다. 범주형 특성에는 'most_frequent'나 'constant'를 쓰세요. KNN 대체는 다변량 구조를 잡을 수 있지만 큰 데이터에선 비쌉니다. 결측 자체가 정보일 수 있으니('is_missing' 지시자 추가) 판단하세요.

machine-learning
import pandas as pd
from sklearn.impute import SimpleImputer, KNNImputer

df = pd.DataFrame({"age": [25, np.nan, 35, 45],
                   "income": [50000, 60000, np.nan, 80000]})

# Drop rows with any missing values (use sparingly)
df_drop = df.dropna()

# Mean/median/mode imputation
imp = SimpleImputer(strategy="median")  # 'mean','most_frequent','constant'
df_imputed = pd.DataFrame(imp.fit_transform(df), columns=df.columns)

# KNN imputer (uses similar samples)
knn_imp = KNNImputer(n_neighbors=3)
df_knn = pd.DataFrame(knn_imp.fit_transform(df), columns=df.columns)

# Always fit imputers on TRAINING data only, then transform test
imp.fit(X_train)
X_train_imp = imp.transform(X_train)
X_test_imp  = imp.transform(X_test)   # uses train medians

스케일링 & 정규화

많은 알고리즘(SVM, KNN, 로지스틱 회귀, 신경망, PCA)은 스케일에 민감합니다 — 트리 모델은 보통 아닙니다. StandardScaler가 기본이고, 경계 범위가 필요하면(예: 이미지) MinMaxScaler, 이상치가 StandardScaler를 왜곡할 때는 RobustScaler입니다. 항상 train에 fit하고 같은 fitted scaler로 test를 transform하세요 — test에 fit_transform 절대 금지.

machine-learning
from sklearn.preprocessing import StandardScaler, MinMaxScaler, RobustScaler

# Standardization: mean 0, std 1 (most common)
scaler = StandardScaler()
X_train_scaled = scaler.fit_transform(X_train)
X_test_scaled  = scaler.transform(X_test)   # use train mean/std!

# Min-max: scale to [0, 1]
minmax = MinMaxScaler()
X_mm = minmax.fit_transform(X_train)

# Robust to outliers: uses median & IQR
robust = RobustScaler()
X_robust = robust.fit_transform(X_train)

범주형 변수 인코딩

LabelEncoder는 타깃용이고, OneHotEncoder는 명목 특성용입니다(본래 순서 없음 — one-hot이 red < green < blue처럼 보이는 것을 피함). OrdinalEncoder는 크기 같은 순서형 범주용입니다. handle_unknown='ignore'가 테스트 시 보지 못한 범주의 오류를 막습니다. 고카디널리티 범주형(예: 우편번호)은 차원 폭발을 피하려 타깃/카운트 인코딩이 더 낫습니다.

machine-learning
from sklearn.preprocessing import LabelEncoder, OneHotEncoder, OrdinalEncoder

# Label encode TARGET (classification): strings -> integers
le = LabelEncoder()
y = le.fit_transform(["cat", "dog", "cat", "bird"])  # [0, 1, 0, 2]
le.inverse_transform([0, 1, 2])                       # back to strings

# One-hot encode FEATURES (nominal, no order)
ohe = OneHotEncoder(sparse_output=False, handle_unknown="ignore")
X_ohe = ohe.fit_transform(df[["color"]])  # red/green/blue -> 3 cols

# Ordinal encode (ordered categories)
oe = OrdinalEncoder(categories=[["low", "medium", "high"]])
X_ord = oe.fit_transform(df[["size"]])

# For high-cardinality features, consider target encoding
# or just drop them if they're IDs.

불균형 데이터 처리

불균형 데이터가 모델을 다수 클래스 쪽으로 기웁니다. 가장 깨끗한 해법은 class_weight='balanced'입니다(데이터 복제 없음). SMOTE가 새 소수 샘플을 합성하지만 노이즈를 만들 수 있으니 — train에만 적용하세요. 오버샘플링과 언더샘플링도 동작하지만 과적합하거나 데이터를 잃을 수 있습니다. 항상 정밀도, 재현율, F1, AUC로 평가하세요 — 불균형 데이터에 정확도만 쓰는 것은 금물입니다.

machine-learning
from sklearn.utils import resample
from imblearn.over_sampling import SMOTE
from sklearn.utils.class_weight import compute_class_weight

# 1. Class weights (no resampling — preferred for trees/linear)
classes = np.unique(y_train)
weights = compute_class_weight("balanced", classes=classes, y=y_train)
class_weight = dict(zip(classes, weights))
model = RandomForestClassifier(class_weight=class_weight)

# 2. Oversample minority
df_majority = df[df.y == 0]
df_minority = df[df.y == 1]
df_minority_up = resample(df_minority, replace=True,
                          n_samples=len(df_majority), random_state=42)

# 3. SMOTE: synthesize new minority samples via k-nearest neighbors
smote = SMOTE(random_state=42)
X_res, y_res = smote.fit_resample(X_train, y_train)

# Always resample on TRAINING data only — never the test set!

이상치 감지

이상치가 평균, 표준편차, 선형 모델을 왜곡합니다. Z-score는 빠르지만 정규성을 가정하고 이상치 자체에 왜곡됩니다(대신 강건한 IQR 사용). Isolation Forest가 고차원과 비선형 경계를 처리합니다. 버릴지, 제한할지(winsorize), 유지할지는 도메인에 따라 결정하세요 — 때로 이상치가 바로 관심 사례입니다(사기, 이상 감지).

machine-learning
import numpy as np
from sklearn.ensemble import IsolationForest

# Z-score: |x - mean| / std > 3 is an outlier
z_scores = np.abs((X - X.mean()) / X.std())
outliers = (z_scores > 3).any(axis=1)

# IQR method (more robust to outliers than z-score)
Q1, Q3 = X.quantile(0.25), X.quantile(0.75)
IQR = Q3 - Q1
outliers_iqr = ((X < (Q1 - 1.5 * IQR)) | (X > (Q3 + 1.5 * IQR))).any(axis=1)

# Isolation Forest (good for high-dimensional data)
iso = IsolationForest(contamination=0.05, random_state=42)
outliers_iso = iso.fit_predict(X)  # -1 = outlier, 1 = inlier

# Remove or cap (winsorize) outliers before training
X_clean = X[~outliers]
03

특성 공학

다항 & 상호작용 특성

PolynomialFeatures가 x^2, x*y 등을 새 특성으로 더해 선형 모델이 비선형 관계를 잡게 합니다. interaction_only가 순수 제곱을 피하며, 교차항만 원할 때 유용합니다. 특성 수가 조합적으로 폭발하므로 — 과적합 방지를 위해 항상 정규화(Ridge/Lasso)와 짝지으거나 차원 축소 뒤에 쓰세요.

machine-learning
from sklearn.preprocessing import PolynomialFeatures

# Generate degree-2 features including interactions
poly = PolynomialFeatures(degree=2, interaction_only=False,
                          include_bias=False)
X_poly = poly.fit_transform(X)
# For X = [a, b], produces: [a, b, a^2, a*b, b^2]

# interaction_only=True keeps just [a, b, a*b] — no squares
poly_int = PolynomialFeatures(degree=2, interaction_only=True,
                              include_bias=False)
X_int = poly_int.fit_transform(X)

# Useful for linear models to capture non-linearity
# WARNING: feature count grows quickly — use with regularization

구간화 & 이산화

구간화가 연속 특성을 이산 버킷으로 바꿔 모델이 비선형 효과를 잡게 하고 이상치 민감도를 줄입니다. 분위수 구간(등빈도)이 등폭 구간의 빈 버킷 문제를 피합니다. 도메인별 구간(예: 연령대)이 자동 구간을 이기는 경우가 많습니다. 모델이 버킷을 별개 범주로 다루도록 구간화된 특성을 one-hot 인코딩하세요.

machine-learning
from sklearn.preprocessing import KBinsDiscretizer
import pandas as pd

# Equal-width bins (uniform spacing)
df["age_bin"] = pd.cut(df["age"], bins=5, labels=False)

# Equal-frequency bins (quantiles — same count per bin)
df["age_quantile"] = pd.qcut(df["age"], q=5, labels=False,
                              duplicates="drop")

# KBinsDiscretizer with strategy
kbd = KBinsDiscretizer(n_bins=5, encode="onehot-dense",
                        strategy="quantile")  # 'uniform','kmeans'
X_binned = kbd.fit_transform(X[["age"]])

# Custom bins with domain knowledge
df["age_group"] = pd.cut(df["age"],
                          bins=[0, 18, 35, 60, 100],
                          labels=["child","young","adult","senior"])

텍스트 특성 추출

Bag-of-words 카운트는 단순하지만 모든 단어를 동등하게 다룹니다; TF-IDF가 문서들에 걸쳐 흔한 단어의 가중치를 낮춥니다. ngram_range=(1,2)가 짧은 구문을 잡습니다. 현대 NLP에는 사전학습 임베딩(sentence-transformers, BERT)을 쓰세요 — bag-of-words가 못 잡는 의미를 담습니다. 어휘 크기와 노이즈 제어에는 항상 max_features와 min_df를 설정하세요.

machine-learning
from sklearn.feature_extraction.text import TfidfVectorizer, CountVectorizer

corpus = [
    "machine learning is fun",
    "deep learning is a subset of machine learning",
    "python is great for data science",
]

# Bag of words (counts)
cv = CountVectorizer(max_features=1000, stop_words="english",
                     ngram_range=(1, 2))
X_counts = cv.fit_transform(corpus)

# TF-IDF: downweights common words
tfidf = TfidfVectorizer(max_features=1000, stop_words="english",
                        ngram_range=(1, 2), min_df=2)
X_tfidf = tfidf.fit_transform(corpus)

# For production, consider sentence-transformers for embeddings:
# from sentence_transformers import SentenceTransformer
# model = SentenceTransformer("all-MiniLM-L6-v2")
# embeddings = model.encode(corpus)

날짜 & 시간 특성

raw datetime 컬럼은 모델에 쓸모가 없습니다 — 의미 있는 부분(시, 요일, 월)을 추출하세요. 주기적 특성(sin/cos)이 연속성을 보존합니다: 23시가 0시와 가까운데, raw 정수 인코딩은 이를 놓칩니다. is_weekend와 공휴일이 인간 주기 패턴을 잡습니다. days_since가 시계열용 간단한 추세 특성입니다.

machine-learning
import pandas as pd

df["date"] = pd.to_datetime(df["date"])

# Extract calendar parts
df["year"]      = df["date"].dt.year
df["month"]     = df["date"].dt.month
df["day"]       = df["date"].dt.day
df["dayofweek"] = df["date"].dt.dayofweek    # 0=Mon
df["dayofyear"] = df["date"].dt.dayofyear
df["hour"]      = df["date"].dt.hour
df["is_weekend"] = df["date"].dt.dayofweek >= 5

# Cyclic encoding (preserves continuity: hour 23 -> 0)
df["hour_sin"] = np.sin(2 * np.pi * df["hour"] / 24)
df["hour_cos"] = np.cos(2 * np.pi * df["hour"] / 24)
df["month_sin"] = np.sin(2 * np.pi * df["month"] / 12)
df["month_cos"] = np.cos(2 * np.pi * df["month"] / 12)

# Time elapsed (useful as a trend feature)
df["days_since"] = (df["date"] - df["date"].min()).dt.days

특성 선택

특성이 많다고 좋은 게 아닙니다 — 무관한 특성이 노이즈와 과적합 위험을 더합니다. SelectKBest가 빠르고 통계적이며, RFE는 철저하지만 느리고(모델을 반복 재학습), SelectFromModel은 트리의 feature_importances_를 일회 필터로 씁니다. 상관 필터가 중복 특성을 저렴하게 제거합니다. 선택은 항상 학습 데이터에만 하고 같은 선택자를 test에 적용하세요.

machine-learning
from sklearn.feature_selection import (SelectKBest, f_classif,
    RFE, SelectFromModel)
from sklearn.ensemble import RandomForestClassifier

# 1. Univariate: keep top-k by statistical test
selector = SelectKBest(f_classif, k=10)
X_new = selector.fit_transform(X, y)
selected = selector.get_support(indices=True)

# 2. Recursive Feature Elimination (model-based, iterative)
rfe = RFE(RandomForestClassifier(random_state=42),
          n_features_to_select=10)
X_rfe = rfe.fit_transform(X, y)

# 3. Select from model importance
sfm = SelectFromModel(RandomForestClassifier(random_state=42),
                      threshold="median")
X_sfm = sfm.fit_transform(X, y)

# 4. Correlation filter — drop one of highly-correlated pairs
corr = pd.DataFrame(X).corr().abs()
to_drop = [c for c in corr.columns
           if any(corr[c] > 0.95)]
X_filtered = X.drop(columns=to_drop)
04

지도 학습

선형 & 로지스틱 회귀

선형 모델은 빠르고 해석 가능하며 강한 기준선입니다. LogisticRegression은 기본 L2 정규화를 씁니다; 낮은 C가 더 강한 정규화입니다. 다중 클래스에는 softmax를 씁니다. 계수가 특성 중요도를 보여주지만 스케일링 후에만 그렇습니다 — 스케일링되지 않은 특성은 계수 비교를 불가하게 만듭니다. 복잡한 모델 전에 항상 선형 기준선으로 시작하세요.

machine-learning
from sklearn.linear_model import LinearRegression, LogisticRegression

# Regression: predict a continuous value
lr = LinearRegression()
lr.fit(X_train, y_train)
y_pred = lr.predict(X_test)

# Inspect coefficients
print("Coef:", lr.coef_, "Intercept:", lr.intercept_)

# Classification: predict a class (uses softmax for multiclass)
clf = LogisticRegression(
    penalty="l2",            # 'l1' (Lasso), 'elasticnet', None
    C=1.0,                   # inverse of regularization strength
    max_iter=1000,
    multi_class="multinomial",
)
clf.fit(X_train, y_train)
y_pred = clf.predict(X_test)
y_proba = clf.predict_proba(X_test)  # class probabilities

결정 트리 & 랜덤 포레스트

결정 트리는 해석 가능하지만 분산이 높습니다 — 작은 데이터 변화가 아주 다른 트리를 만듭니다. 랜덤 포레스트는 부트스트랩 샘플과 무작위 특성 부분집합으로 학습한 많은 트리를 평균해(bagging) 이를 고칩니다. 분류 표준은 max_features='sqrt'입니다. 포레스트의 특성 중요도는 고카디널리티 특성에 편향되므로 — 더 공정한 뷰를 위해 permutation_importance를 시도하세요.

machine-learning
from sklearn.tree import DecisionTreeClassifier
from sklearn.ensemble import RandomForestClassifier

# Single tree (high variance, easy to overfit)
tree = DecisionTreeClassifier(
    max_depth=5,              # limit depth to prevent overfitting
    min_samples_leaf=10,      # min samples per leaf
    random_state=42,
)
tree.fit(X_train, y_train)

# Random forest: ensemble of trees on bootstrapped samples
rf = RandomForestClassifier(
    n_estimators=200,         # number of trees
    max_depth=None,
    max_features="sqrt",      # features per split
    n_jobs=-1,                # use all CPUs
    random_state=42,
)
rf.fit(X_train, y_train)

# Feature importance (averaged across trees)
importances = pd.Series(rf.feature_importances_, index=X.columns)

그라디언트 부스팅 (XGBoost / LightGBM)

그라디언트 부스팅이 트리를 순차적으로 쌓아 각각이 이전의 오류를 교정합니다 — 표 형식 데이터에서 보통 최고 성능입니다. sklearn의 GradientBoosting은 느리고, HistGradientBoosting이 빠른 히스토그램 기반 등가물입니다. XGBoost와 LightGBM이 프로덕션/대회 표준이며 네이티브 결측값 처리와 early stopping을 지원합니다. 최적 트리 수를 찾으려 검증 셋과 함께 항상 early_stopping을 쓰세요.

machine-learning
from sklearn.ensemble import GradientBoostingClassifier, HistGradientBoostingClassifier
import lightgbm as lgb
import xgboost as xgb

# sklearn (slow on large data)
gbm = GradientBoostingClassifier(
    n_estimators=200, learning_rate=0.1, max_depth=3, random_state=42)
gbm.fit(X_train, y_train)

# sklearn's faster histogram-based version (like LightGBM)
hgbm = HistGradientBoostingClassifier(
    max_iter=200, learning_rate=0.1, max_leaf_nodes=31, random_state=42)
hgbm.fit(X_train, y_train)

# XGBoost (popular in competitions)
xgb_clf = xgb.XGBClassifier(
    n_estimators=200, learning_rate=0.1, max_depth=6,
    subsample=0.8, colsample_bytree=0.8, n_jobs=-1,
    eval_metric="logloss", random_state=42)
xgb_clf.fit(X_train, y_train, eval_set=[(X_val, y_val)], early_stopping_rounds=10)

# LightGBM (fastest on large data)
lgb_clf = lgb.LGBMClassifier(n_estimators=200, learning_rate=0.1, num_leaves=31)
lgb_clf.fit(X_train, y_train, eval_set=(X_val, y_val))

서포트 벡터 머신

SVM이 클래스를 나누는 최대 마진 초평면을 찾습니다 — 명확한 경계를 가진 소중형 데이터셋에 강력합니다. 특성 스케일링이 필수입니다(SVM은 거리 기반). RBF 커널이 비선형을 처리하며, C(정규화)와 gamma(커널 폭)를 그리드 검색으로 조율하세요. SVC는 샘플에 따라 확장이 나쁩니다(O(n^2)–O(n^3)) — 5만 샘플 이상에는 LinearSVC나 트리 앙상블을 쓰세요.

machine-learning
from sklearn.svm import SVC, SVR
from sklearn.preprocessing import StandardScaler

# SVC requires scaling!
scaler = StandardScaler()
X_train_s = scaler.fit_transform(X_train)
X_test_s  = scaler.transform(X_test)

# Kernels: 'linear', 'rbf' (Gaussian), 'poly', 'sigmoid'
svm = SVC(
    kernel="rbf",
    C=1.0,              # regularization (higher = fit harder)
    gamma="scale",      # kernel width
    probability=True,   # enable predict_proba (slower)
    random_state=42,
)
svm.fit(X_train_s, y_train)
y_pred = svm.predict(X_test_s)

# SVR for regression
svr = SVR(kernel="rbf", C=1.0, epsilon=0.1)
svr.fit(X_train_s, y_train)

k-최근접 이웃

KNN이 가장 단순한 ML 알고리즘입니다: 학습 데이터를 저장하고 k개 최근접 이웃의 투표로 예측합니다. 스케일링이 필수입니다(거리 기반). 작은 k = 낮은 편향/높은 분산(과적합), 큰 k = 높은 편향/낮은 분산(과소적합)입니다. KNN은 큰 데이터셋에서 예측이 느립니다 — 프로덕션에는 근사 최근접 이웃(FAISS, HNSW)을 쓰세요.

machine-learning
from sklearn.neighbors import KNeighborsClassifier, KNeighborsRegressor

# KNN: classify by majority vote of k nearest training samples
knn = KNeighborsClassifier(
    n_neighbors=5,        # k — try odd values to break ties
    weights="uniform",    # or 'distance' (closer = more weight)
    metric="minkowski",   # 'euclidean','manhattan', etc.
    p=2,                  # 2=euclidean, 1=manhattan
    n_jobs=-1,
)
knn.fit(X_train_scaled, y_train)
y_pred = knn.predict(X_test_scaled)

# Choose k via cross-validation
from sklearn.model_selection import cross_val_score
for k in [1, 3, 5, 7, 9, 11]:
    score = cross_val_score(KNeighborsClassifier(n_neighbors=k),
                            X_train_scaled, y_train, cv=5).mean()
    print(f"k={k}: {score:.3f}")
05

비지도 학습

K-Means 클러스터링

K-Means가 클러스터 내 분산을 최소화해 데이터를 k개 구형 클러스터로 나눕니다. n_init=10이 알고리즘을 10개 무작위 초기화로 실행하고 최선을 유지합니다(sklearn 1.4에서 기본값이 바뀜). k는 팔꿈치(inertia)나 실루엣 점수로 고르세요(실루엣이 더 원칙적). K-Means는 구형·동일 크기 클러스터를 가정하므로 — 비구형 클러스터에는 DBSCAN이나 Gaussian Mixture를 쓰세요.

machine-learning
from sklearn.cluster import KMeans
from sklearn.metrics import silhouette_score

# Choose k via the elbow method or silhouette score
inertias, silhouettes = [], []
for k in range(2, 11):
    km = KMeans(n_clusters=k, n_init=10, random_state=42)
    labels = km.fit_predict(X)
    inertias.append(km.inertia_)
    silhouettes.append(silhouette_score(X, labels))

# Final model with chosen k
kmeans = KMeans(n_clusters=4, n_init=10, random_state=42)
clusters = kmeans.fit_predict(X)
centers = kmeans.cluster_centers_

# Predict cluster for new points
new_labels = kmeans.predict(X_new)

DBSCAN (밀도 기반)

DBSCAN이 임의 모양의 클러스터를 찾고 이상치(-1로 라벨됨)를 자동 감지합니다 — k를 지정할 필요가 없습니다. eps가 핵심 매개변수이며, k-거리 플롯(정렬된 k-최근접 이웃 거리의 '팔꿈치')으로 조율하세요. min_samples가 노이즈 민감도를 제어합니다. DBSCAN은 가변 밀도에 약합니다 — HDBSCAN이 그걸 더 잘 다룹니다. 새 점을 직접 예측할 수 없으니; 재학습하거나 HDBSCAN의 approximate_predict를 쓰세요.

machine-learning
from sklearn.cluster import DBSCAN

# DBSCAN groups densely-connected points; marks sparse ones as noise (-1)
db = DBSCAN(
    eps=0.5,            # max distance between points in a cluster
    min_samples=5,      # min points to form a dense region
    metric="euclidean",
)
labels = db.fit_predict(X)
n_clusters = len(set(labels)) - (1 if -1 in labels else 0)
n_noise = list(labels).count(-1)

# Tune eps via the k-distance plot (k = min_samples)
from sklearn.neighbors import NearestNeighbors
nn = NearestNeighbors(n_neighbors=5).fit(X)
distances, _ = nn.kneighbors(X)
distances = np.sort(distances[:, -1])

# DBSCAN doesn't have predict() — refit to predict on new data
# Or use HDBSCAN for a more robust, parameter-light alternative

계층적 클러스터링

계층적 클러스터링이 중첩 클러스터의 트리(덴드로그램)를 만듭니다 — 여러 세분성에서 클러스터 구조를 이해하고 싶을 때 유용합니다. 덴드로그램이 임의 클러스터 수를 위한 절단 지점을 시각적으로 보여줍니다. 'ward' 연결(클러스터 내 분산 최소화)이 가장 흔하고, 'single'은 취약합니다(사슬화). AgglomerativeClustering은 약 1만 샘플을 넘으면 확장이 나쁩니다 — 큰 데이터에는 K-Means나 HDBSCAN을 쓰세요.

machine-learning
from sklearn.cluster import AgglomerativeClustering
from scipy.cluster.hierarchy import dendrogram, linkage
import matplotlib.pyplot as plt

# Compute linkage matrix (for dendrogram)
Z = linkage(X, method="ward")  # 'ward','complete','average','single'

# Plot dendrogram to choose number of clusters
plt.figure(figsize=(10, 5))
dendrogram(Z, truncate_mode="level", p=5)
plt.axhline(y=Z[-4, 2], color="r", linestyle="--")  # cut at 4 clusters
plt.show()

# Agglomerative clustering with chosen k
agg = AgglomerativeClustering(
    n_clusters=4,
    linkage="ward",   # minimizes variance
    metric="euclidean",
)
labels = agg.fit_predict(X)

가우시안 혼합 모델

GMM이 K-Means의 확률적 대응물입니다: 각 클러스터가 자체 평균과 공분산을 가진 가우시안이라 타원형 클러스터를 처리하고 소프트 할당(확률)을 줍니다. covariance_type='full'이 가장 유연하지만 매개변수가 많고, 'diag'가 좋은 절충입니다. k는 BIC로 고르세요(낮을수록 좋음). GMM은 새 샘플도 생성할 수 있습니다 — 데이터 증강에 유용합니다.

machine-learning
from sklearn.mixture import GaussianMixture

# GMM: probabilistic clustering — each cluster is a Gaussian
gmm = GaussianMixture(
    n_components=4,
    covariance_type="full",  # 'spherical','tied','diag','full'
    n_init=10,
    random_state=42,
)
gmm.fit(X)

labels = gmm.predict(X)
probs = gmm.predict_proba(X)   # soft clustering (responsibilities)

# Generative: sample new data
X_sampled, y_sampled = gmm.sample(100)

# Choose n_components via BIC (lower is better)
bics = []
for k in range(1, 11):
    g = GaussianMixture(n_components=k, n_init=10, random_state=42).fit(X)
    bics.append(g.bic(X))

이상 감지

이상 감지가 희귀하고 수상한 항목을 식별합니다 — 사기, 결함, 침입. Isolation Forest가 만능 승자입니다(빠름, 잘 확장됨, 고차원 처리). One-Class SVM은 깨끗한 '정상' 학습 셋이 있을 때 잘 동작합니다. LOF가 전역 메서드가 놓치는 국소 이상을 잡습니다. contamination이 기대 이상 비율을 정합니다; 도메인 지식에 따라 조율하세요.

machine-learning
from sklearn.ensemble import IsolationForest
from sklearn.svm import OneClassSVM
from sklearn.neighbors import LocalOutlierFactor

# Isolation Forest: isolates anomalies with shallow trees
iso = IsolationForest(contamination=0.05, random_state=42)
labels = iso.fit_predict(X)  # -1 anomaly, 1 normal
scores = iso.decision_function(X)  # lower = more anomalous

# One-Class SVM: learns a boundary around normal data
ocsvm = OneClassSVM(kernel="rbf", nu=0.05, gamma="scale")
labels = ocsvm.fit_predict(X_train_normal)

# Local Outlier Factor: density-based (good for local anomalies)
lof = LocalOutlierFactor(n_neighbors=20, contamination=0.05)
labels = lof.fit_predict(X)
# For new data: lof.negative_outlier_factor_ (lower = more anomalous)
06

회귀

선형 회귀 & 정규화 변형

OLS가 정규화 없이 제곱 오류를 최소화합니다 — 다중공선성 데이터에서 분산이 높습니다. Ridge(L2)가 계수를 부드럽게 줄여 많은 특성이 관여할 때 좋습니다. Lasso(L1)가 일부 계수를 0으로 몰아 특성 선택을 수행합니다. ElasticNet이 둘을 섞어 특성이 상관될 때 유용합니다. 패널티가 특성 전반에 공정해지도록 정규화 회귀 전에 항상 특성을 스케일하세요.

machine-learning
from sklearn.linear_model import LinearRegression, Ridge, Lasso, ElasticNet

# Ordinary Least Squares
ols = LinearRegression()
ols.fit(X_train, y_train)

# Ridge (L2): shrinks coefficients, keeps all features
ridge = Ridge(alpha=1.0)
ridge.fit(X_train_scaled, y_train)

# Lasso (L1): shrinks some coefficients to 0 (feature selection)
lasso = Lasso(alpha=0.1, max_iter=10000)
lasso.fit(X_train_scaled, y_train)
print("Non-zero coefs:", (lasso.coef_ != 0).sum())

# ElasticNet: mix of L1 and L2
en = ElasticNet(alpha=0.1, l1_ratio=0.5)  # l1_ratio=1 -> pure Lasso
en.fit(X_train_scaled, y_train)

회귀 평가 지표

RMSE가 큰 오류에(제곱) 패널티를 주며 y와 같은 단위입니다 — 가장 흔한 지표. MAE가 더 해석 가능하고 이상치에 강합니다. R2가 설명된 분산 비율입니다; 0은 모델이 평균 예측보다 나은 게 없다는 뜻입니다. MAPE가 백분율 오류를 주지만 y=0일 때 정의되지 않습니다. 비용에 따라 지표를 고르세요: 큰 오류가 치명적이면 RMSE, 모든 오류의 비용이 같으면 MAE.

machine-learning
from sklearn.metrics import (mean_squared_error, mean_absolute_error,
    r2_score, mean_absolute_percentage_error)

y_pred = model.predict(X_test)

mse  = mean_squared_error(y_test, y_pred)         # sensitive to outliers
rmse = np.sqrt(mse)                                # same units as y
mae  = mean_absolute_error(y_test, y_pred)         # robust to outliers
r2   = r2_score(y_test, y_pred)                    # 1=perfect, 0=mean, <0=worse
mape = mean_absolute_percentage_error(y_test, y_pred)  # % error

print(f"RMSE: {rmse:.3f}")
print(f"MAE:  {mae:.3f}")
print(f"R2:   {r2:.3f}")
print(f"MAPE: {mape:.1%}")

# Adjusted R2 accounts for number of features
n, p = X_test.shape
adj_r2 = 1 - (1 - r2) * (n - 1) / (n - p - 1)

결정 트리 회귀

트리 기반 회귀기가 계단식 상수 예측을 만듭니다 — 학습 데이터 범위 밖으로는 외삽할 수 없습니다. 랜덤 포레스트가 평균으로 분산을 줄이고, 그라디언트 부스팅이 순차 교정으로 편향을 줄입니다. 분위수 회귀(loss='quantile')가 평균 대신 백분위를 예측합니다 — 하/상 분위수 모델을 결합해 예측 구간을 만들면, 불확실성 추정이 필요할 때 유용합니다.

machine-learning
from sklearn.tree import DecisionTreeRegressor
from sklearn.ensemble import RandomForestRegressor, GradientBoostingRegressor

# Single tree (piecewise constant predictions)
dt = DecisionTreeRegressor(max_depth=5, min_samples_leaf=10,
                            random_state=42)
dt.fit(X_train, y_train)

# Random forest regressor (averages trees)
rf = RandomForestRegressor(n_estimators=200, max_features="sqrt",
                            n_jobs=-1, random_state=42)
rf.fit(X_train, y_train)

# Gradient boosting regressor
gb = GradientBoostingRegressor(n_estimators=200, learning_rate=0.1,
                                max_depth=3, random_state=42)
gb.fit(X_train, y_train)

# Quantile regression — predict ranges instead of points
from sklearn.ensemble import GradientBoostingRegressor
gbr_lower = GradientBoostingRegressor(loss="quantile", alpha=0.1)
gbr_upper = GradientBoostingRegressor(loss="quantile", alpha=0.9)
gbr_lower.fit(X_train, y_train)
gbr_upper.fit(X_train, y_train)

정규화 경로

정규화 경로가 alpha가 커질수록 Lasso 계수가 0으로 수축하는 모습을 보여줍니다 — 다른 패널티 강도에서의 특성 중요도 시각화입니다. 높은 alpha에서 살아남는 특성이 가장 예측력 있습니다. 어떤 특성이 중요한지 이해하고 교차 검증 전 합리적 alpha 범위를 고르는 훌륭한 진단 도구입니다.

machine-learning
import numpy as np
import matplotlib.pyplot as plt
from sklearn.linear_model import lasso_path

# Compute Lasso coefficients for many alpha values
alphas, coefs, _ = lasso_path(X_train_scaled, y_train,
                               alphas=np.logspace(-3, 1, 100))

# Plot: each line is a coefficient vs alpha
plt.figure(figsize=(8, 5))
for coef in coefs:
    plt.plot(alphas, coef)
plt.xscale("log")
plt.xlabel("alpha (regularization strength)")
plt.ylabel("coefficient")
plt.title("Lasso regularization path")
plt.axhline(0, color="k", lw=0.5)
plt.show()

잔차 분석

잔차 플롯이 모델 오스펙을 진단합니다. 0 주위의 무작위 구름은 모델이 잘 맞는다는 뜻이고, U자형은 비선형성 누락을(다항 특성 추가나 트리 사용), 깔때기형은 이분산성을(y를 로그 변환) 시사합니다. 잔차의 정규성은 추론(신뢰 구간)에는 중요하지만 예측 정확도에는 그렇지 않습니다.

machine-learning
import matplotlib.pyplot as plt
import seaborn as sns

residuals = y_test - y_pred

fig, axes = plt.subplots(1, 2, figsize=(12, 5))

# 1. Residuals vs predicted — should look random around 0
axes[0].scatter(y_pred, residuals, alpha=0.5)
axes[0].axhline(0, color="r", linestyle="--")
axes[0].set_xlabel("Predicted"); axes[0].set_ylabel("Residual")

# 2. Residual distribution — should be ~normal
sns.histplot(residuals, kde=True, ax=axes[1])
axes[1].set_xlabel("Residual")

plt.show()

# Patterns in residuals suggest model issues:
# - U-shape: missing non-linearity (add polynomial features)
# - Funnel: heteroscedasticity (try log-transforming y)
# - Skew: try transforming y or use a different loss
07

분류

이진 분류 기본

predict가 하드 클래스 라벨을 반환하고(임계값 0.5), predict_proba가 확률을 반환합니다 — 보통 더 유용합니다. 기본 0.5 임계값은 거의 최적이 아닙니다: 더 높은 재현율(더 많은 양성 포착, 예: 암 검진)에는 낮추고, 더 높은 정밀도(거짓 경보 감소, 예: 스팸 필터)에는 올리세요. ROC-AUC가 확률이 양성을 음성보다 얼마나 잘 순위 매기는지 임계값과 무관하게 측정합니다.

machine-learning
from sklearn.linear_model import LogisticRegression
from sklearn.metrics import (confusion_matrix, classification_report,
    roc_auc_score, precision_recall_curve)

clf = LogisticRegression(max_iter=1000)
clf.fit(X_train, y_train)
y_pred = clf.predict(X_test)
y_proba = clf.predict_proba(X_test)[:, 1]  # P(class=1)

# Confusion matrix: TN FP / FN TP
cm = confusion_matrix(y_test, y_pred)
print(cm)
print(classification_report(y_test, y_pred))

# Adjust threshold (default 0.5) to trade precision for recall
y_pred_custom = (y_proba > 0.3).astype(int)  # higher recall

# ROC-AUC: probability ranking quality (threshold-independent)
print("ROC-AUC:", roc_auc_score(y_test, y_proba))

혼동 행렬 & 파생 지표

정확도는 불균형 데이터에서 오도적입니다 — 99%가 음성인 데이터셋은 모든 것을 음성으로 예측해 99% 정확도를 얻습니다. 정밀도와 재현율이 정밀도-재현율 트레이드오프를 드러냅니다: 정밀도는 '예측된 양성 중 몇 개가 진짜인가?', 재현율은 '실제 양성 중 몇 개를 잡았는가?'에 답합니다. F1이 조화평균입니다. 클래스가 동등하게 가중되어야 하면 macro 평균, 빈도를 반영해야 하면 weighted를 쓰세요.

machine-learning
from sklearn.metrics import (confusion_matrix, precision_score,
    recall_score, f1_score)

# Binary: confusion_matrix returns [[TN, FP], [FN, TP]]
tn, fp, fn, tp = confusion_matrix(y_test, y_pred).ravel()

accuracy  = (tp + tn) / (tp + tn + fp + fn)
precision = tp / (tp + fp)    # of predicted positives, how many correct
recall    = tp / (tp + fn)    # of actual positives, how many caught
f1        = 2 * precision * recall / (precision + recall)  # harmonic mean
specificity = tn / (tn + fp)  # true negative rate

# sklearn shortcuts
print("Precision:", precision_score(y_test, y_pred))
print("Recall:    ", recall_score(y_test, y_pred))
print("F1:        ", f1_score(y_test, y_pred))

# Multi-class: average='macro' (unweighted) or 'weighted' (by class size)
print("Macro F1:", f1_score(y_test, y_pred, average="macro"))

ROC & PR 곡선

ROC 곡선이 임계값에 걸쳐 재현율(TPR)을 거짓 양성률에 대해 그립니다; 곡선 아래 면적(AUC)이 순위 품질을 요약합니다(0.5 = 무작위, 1.0 = 완벽). PR 곡선이 불균형 데이터에서 ROC보다 정보적입니다 — 음성이 지배하면 ROC가 속기 쉽게 좋아 보일 수 있습니다. ROC에서는 왼쪽 위, PR에서는 오른쪽 위를 노리세요.

machine-learning
from sklearn.metrics import (roc_curve, precision_recall_curve,
    auc, RocCurveDisplay, PrecisionRecallDisplay)
import matplotlib.pyplot as plt

# ROC curve: TPR (recall) vs FPR at all thresholds
fpr, tpr, thresholds = roc_curve(y_test, y_proba)
roc_auc = auc(fpr, tpr)

# PR curve: precision vs recall (better for imbalanced data)
prec, rec, thresholds = precision_recall_curve(y_test, y_proba)
pr_auc = auc(rec, prec)

fig, axes = plt.subplots(1, 2, figsize=(12, 5))
RocCurveDisplay.from_predictions(y_test, y_proba, ax=axes[0])
PrecisionRecallDisplay.from_predictions(y_test, y_proba, ax=axes[1])
axes[0].set_title(f"ROC (AUC={roc_auc:.3f})")
axes[1].set_title(f"PR (AUC={pr_auc:.3f})")
plt.show()

다중 클래스 분류

N>2 클래스에서 LogisticRegression은 softmax를 씁니다(multi_class='multinomial'). 클래스별 정밀도/재현율이 모델이 어떤 클래스들을 혼동하는지 보여줍니다. 혼동 행렬을 행별(진짜 클래스)로 정규화하면 클래스별 재현율이 보여 체계적으로 오분류되는 범주를 찾는 데 유용합니다. Cohen's kappa가 우연 일치를 보정한 정확도를 주고, log_loss가 예측 확률의 품질을 측정합니다(낮을수록 좋음).

machine-learning
from sklearn.linear_model import LogisticRegression
from sklearn.metrics import (cohen_kappa_score, log_loss,
    classification_report, confusion_matrix, ConfusionMatrixDisplay)

# Multiclass: logistic regression uses softmax by default
clf = LogisticRegression(multi_class="multinomial", max_iter=1000)
clf.fit(X_train, y_train)
y_pred = clf.predict(X_test)
y_proba = clf.predict_proba(X_test)

# Per-class report
print(classification_report(y_test, y_pred))

# Confusion matrix (now NxN)
disp = ConfusionMatrixDisplay.from_predictions(
    y_test, y_pred, display_labels=clf.classes_,
    cmap="Blues", normalize="true")  # normalize per true class

# Multiclass metrics
print("Cohen's kappa:", cohen_kappa_score(y_test, y_pred))
print("Log loss:     ", log_loss(y_test, y_proba))

확률 보정

80% 예측 확률의 모델은 80%의 시간에 맞아야 하지만 — 많은 분류기(Random Forest, SVM, Naive Bayes)가 보정되지 않은 점수를 출력합니다. CalibratedClassifierCV가 분리된 셋에서 아이소토닉 회귀나 시그모이드를 fit해 이를 고칩니다. 보정은 확률에 따라 행동할 때(위험 점수화, 임계값 조율) 중요합니다 — 하드 클래스 예측만 쓴다면 필요 없습니다.

machine-learning
from sklearn.calibration import CalibratedClassifierCV, calibration_curve
import matplotlib.pyplot as plt

# Many classifiers output poorly-calibrated probabilities
# (e.g. Random Forest, SVM). Calibrate them.

# Method 1: isotonic regression (more flexible, needs more data)
# Method 2: sigmoid (Platt scaling) — parametric, works with less data
calibrated = CalibratedClassifierCV(rf, method="isotonic", cv=5)
calibrated.fit(X_train, y_train)
y_proba = calibrated.predict_proba(X_test)[:, 1]

# Calibration curve: predicted prob vs observed frequency
prob_true, prob_pred = calibration_curve(y_test, y_proba, n_bins=10)
plt.plot([0, 1], [0, 1], "k--")
plt.plot(prob_pred, prob_true, "s-")
plt.xlabel("Predicted probability"); plt.ylabel("Observed frequency")
plt.show()
08

클러스터링 심화

k 고르기: 팔꿈치 & 실루엣

팔꿈치 방법이 inertia가 빠르게 떨어지지 않기 시작하는 k를 찾습니다 — 주관적이고 때로 보이지 않습니다. 실루엣 점수가 더 원칙적입니다: 각 점이 자기 클러스터와 가장 가까운 타 클러스터와 얼마나 유사한지 측정합니다(범위 -1~1). 실루엣 > 0.5는 합리적 구조, > 0.7은 강력합니다. 항상 둘 다 시각화하고 팔꿈치가 불명확하면 실루엣을 선호하세요.

machine-learning
from sklearn.cluster import KMeans
from sklearn.metrics import silhouette_score, silhouette_samples
import matplotlib.pyplot as plt

# Elbow method: inertia (sum of squared distances to centroid)
inertias = []
for k in range(1, 11):
    km = KMeans(n_clusters=k, n_init=10, random_state=42).fit(X)
    inertias.append(km.inertia_)

plt.plot(range(1, 11), inertias, "o-")
plt.xlabel("k"); plt.ylabel("Inertia"); plt.title("Elbow method")
plt.show()

# Silhouette: -1 (bad) to 1 (well-clustered), 0 = on boundary
silhouettes = []
for k in range(2, 11):
    labels = KMeans(n_clusters=k, n_init=10, random_state=42).fit_predict(X)
    silhouettes.append(silhouette_score(X, labels))

실루엣 플롯

실루엣 플롯이 모든 샘플의 실루엣 계수를 클러스터별로 보여줍니다. 같은 너비의 '칼' 모양은 균형 잡힌 클러스터를, 불균일한 너비는 일부 클러스터가 지배한다는 뜻입니다. 빨간 점선이 평균입니다 — 이 선 아래의 클러스터는 분리가 잘 안 된 것입니다. 이 플롯으로 다른 k 값들을 시각적으로 비교하세요.

machine-learning
from sklearn.metrics import silhouette_samples
import matplotlib.pyplot as plt
import numpy as np

k = 4
km = KMeans(n_clusters=k, n_init=10, random_state=42).fit(X)
labels = km.labels_
sil_values = silhouette_samples(X, labels)

fig, ax = plt.subplots(figsize=(8, 6))
y_lower = 10
for i in range(k):
    ith = np.sort(sil_values[labels == i])
    y_upper = y_lower + len(ith)
    ax.fill_betweenx(np.arange(y_lower, y_upper), 0, ith, alpha=0.7)
    ax.text(-0.05, (y_lower + y_upper) / 2, str(i))
    y_lower = y_upper + 10
ax.axvline(sil_values.mean(), color="red", linestyle="--")
ax.set_xlabel("Silhouette coefficient"); ax.set_ylabel("Cluster")
plt.show()

HDBSCAN (계층적 DBSCAN)

HDBSCAN이 DBSCAN의 가장 큰 약점 — eps 조율 필요성 — 을 고칩니다. 가변 밀도 수준에 걸쳐 계층을 만들고 안정적인 클러스터를 추출해, 클러스터 밀도가 가변적인 데이터에서 동작합니다. min_cluster_size가 주 매개변수이며 직관적입니다(관심 있는 최소 클러스터 크기). 희박 지역의 점들은 -1(노이즈) 라벨을 받습니다. HDBSCAN이 실제 데이터에서 K-Means보다 더 의미 있는 클러스터를 내는 경우가 많습니다.

machine-learning
import hdbscan  # pip install hdbscan

# HDBSCAN: DBSCAN that automatically chooses eps via hierarchy
clusterer = hdbscan.HDBSCAN(
    min_cluster_size=5,   # min points to form a cluster
    min_samples=None,     # how conservative to be about noise
    metric="euclidean",
    cluster_selection_method="eom",  # 'leaf' for fine-grained
)
labels = clusterer.fit_predict(X)

# Soft clustering: probability of cluster membership
probs = clusterer.probabilities_

# Compare clusters across parameter settings
clusterer.condensed_tree_.plot()

클러스터링 평가

내부 지표(실루엣, Davies-Bouldin, Calinski-Harabasz)가 정답 없이 클러스터 품질을 평가합니다 — 모델 선택에 유용합니다. 외부 지표(ARI, NMI)가 클러스터링을 알려진 라벨과 비교합니다 — 라벨 있는 데이터 벤치마킹에 유용합니다. ARI와 NMI 둘 다 우연을 보정하고 순열 불변입니다. 최고의 단일 지표는 없습니다 — 여러 개를 쓰고 클러스터를 시각화하세요.

machine-learning
from sklearn.metrics import (silhouette_score, davies_bouldin_score,
    calinski_harabasz_score, adjusted_rand_score, normalized_mutual_info_score)

# Internal metrics (no ground truth)
print("Silhouette:        ", silhouette_score(X, labels))      # higher = better
print("Davies-Bouldin:    ", davies_bouldin_score(X, labels))   # lower = better
print("Calinski-Harabasz: ", calinski_harabasz_score(X, labels)) # higher = better

# External metrics (when you have ground-truth labels)
true_labels = y  # e.g. the actual iris species
print("Adjusted Rand:    ", adjusted_rand_score(true_labels, labels))
print("NMI:              ", normalized_mutual_info_score(true_labels, labels))

# ARI and NMI: 0 = random, 1 = perfect match
# Both are invariant to label permutations (cluster 1 vs cluster 2 doesn't matter)

클러스터링용 차원 축소

고차원에서의 클러스터링은 차원의 저주로 고통받습니다 — 거리가 무의미해집니다. 먼저 PCA(선형, 빠름)나 UMAP(비선형, 국소 구조 보존)으로 5-50차원으로 줄이세요. t-SNE는 시각화 전용입니다(새 데이터에 대한 transform 메서드가 없고, 왜곡 때문에 클러스터링 입력으로 부적합). 클러스터는 항상 t-SNE나 UMAP으로 2D 시각화하세요.

machine-learning
from sklearn.decomposition import PCA, UMAP  # umap-learn package
from sklearn.manifold import TSNE
from sklearn.cluster import KMeans

# Reduce dimensions BEFORE clustering high-dim data
# PCA: linear, fast, preserves global structure
pca = PCA(n_components=10, random_state=42).fit(X)
X_pca = pca.transform(X)

# UMAP: non-linear, fast, preserves local+global structure
reducer = UMAP(n_components=5, random_state=42)
X_umap = reducer.fit_transform(X)

# t-SNE: visualization only (no transform on new data)
X_tsne = TSNE(n_components=2, perplexity=30, random_state=42).fit_transform(X)

# Cluster on the embeddings
labels = KMeans(n_clusters=4, n_init=10, random_state=42).fit_predict(X_umap)

# Plot 2D embedding colored by cluster
plt.scatter(X_tsne[:, 0], X_tsne[:, 1], c=labels, cmap="tab10", s=10)
plt.show()
09

차원 축소

PCA (주성분 분석)

PCA가 가장 많은 분산을 잡는 직교 축(주성분)을 찾아 대부분의 정보를 보존하며 고차원 데이터를 압축하게 합니다. 스케일링이 중요합니다 — PCA가 특성 스케일에 민감합니다. 95% 분산을 자동 유지하려 n_components=0.95를 쓰세요. PCA는 선형이고 빠르며 분산 = 정보를 가정하는데 — 항상 참은 아닙니다(저분산 특성이 판별적인 경우가 있습니다).

machine-learning
from sklearn.decomposition import PCA

# PCA finds orthogonal axes of maximum variance
pca = PCA(n_components=2, random_state=42)
X_pca = pca.fit_transform(X_scaled)   # scaling matters!

# Explained variance: how much info each PC retains
print("Explained variance ratio:", pca.explained_variance_ratio_)
print("Total retained:", pca.explained_variance_ratio_.sum())

# Choose n_components to retain 95% of variance
pca_full = PCA(n_components=0.95, random_state=42).fit(X_scaled)
print("Components for 95%:", pca_full.n_components_)
X_reduced = pca_full.transform(X_scaled)

# Reconstruct (lossy) from compressed representation
X_reconstructed = pca_full.inverse_transform(X_reduced)

시각화용 t-SNE

t-SNE가 고차원 데이터의 2D/3D 시각화에 탁월하며 국소 이웃을 보존해 클러스터가 시각적으로 나타납니다. perplexity(보통 5-50)가 국소 vs 전역 구조의 균형을 제어합니다. t-SNE 왜곡: 클러스터 크기와 클러스터 간 거리는 의미 없습니다 — 국소 이웃만 의미 있습니다. 큰 데이터에서 느리므로 — t-SNE 전에 PCA로 차원을 먼저 줄이세요(예: 50까지).

machine-learning
from sklearn.manifold import TSNE
import matplotlib.pyplot as plt

# t-SNE is for 2D/3D visualization, NOT as preprocessing
tsne = TSNE(
    n_components=2,
    perplexity=30,         # try 5-50; ~ sqrt(n_samples) is a heuristic
    learning_rate="auto",
    n_iter=1000,
    init="pca",            # better than random init
    random_state=42,
)
X_tsne = tsne.fit_transform(X_scaled)

plt.scatter(X_tsne[:, 0], X_tsne[:, 1], c=y, cmap="tab10", s=10)
plt.colorbar(); plt.show()

UMAP

UMAP이 t-SNE의 현대적 대안입니다: 더 빠르고, 더 잘 확장되며, 국소와 전역 구조를 모두 보존하고, 결정적으로 새 데이터에 대한 transform을 지원해 파이프라인 단계가 될 수 있습니다. n_neighbors가 국소 vs 전역 트레이드오프를 제어합니다(작음 = 국소 세부, 큼 = 전역 구조); min_dist가 점들이 얼마나 촘촘히 모이는지 제어합니다. ML 파이프라인에서는 UMAP으로 2가 아니라 5-50차원으로 압축하세요.

machine-learning
from umap import UMAP  # pip install umap-learn

# UMAP: faster than t-SNE, preserves more global structure,
# and supports transform on new data (good for ML pipelines)
reducer = UMAP(
    n_components=2,
    n_neighbors=15,    # smaller = local, larger = global
    min_dist=0.1,      # how tightly points pack
    metric="euclidean",
    random_state=42,
)
X_umap = reducer.fit_transform(X_scaled)

# Can transform new data (unlike t-SNE)
X_new_umap = reducer.transform(X_new)

# Use in a pipeline as a preprocessor before clustering/classification
from sklearn.pipeline import Pipeline
pipe = Pipeline([
    ("umap", UMAP(n_components=5, random_state=42)),
    ("clf",  RandomForestClassifier(random_state=42)),
])

LDA (선형 판별 분석)

PCA(비지도)와 달리 LDA가 클래스 라벨을 써 클래스 간 분산을 최대화하면서 클래스 내 분산을 최소화하는 투영을 찾습니다. 최대 n_components는 n_classes - 1이라 클래스 수가 적은 문제에만 유용합니다. LDA는 선형 분류기 역할도 합니다(공유 공분산의 가우시안 클래스 가정). 라벨이 있고 클래스 분리성을 최대화하는 차원 축소를 원할 때 LDA를 쓰세요.

machine-learning
from sklearn.discriminant_analysis import LinearDiscriminantAnalysis

# LDA is SUPERVISED dimensionality reduction — uses class labels
# to find axes that best separate classes
lda = LinearDiscriminantAnalysis(n_components=2)
X_lda = lda.fit_transform(X_train, y_train)  # note: y_train passed in

# Also a classifier (Gaussian model per class)
y_pred = lda.predict(X_test)

# Max n_components = n_classes - 1
# For 3 classes, you get at most 2 LDA components

# Compare: PCA ignores class labels (unsupervised);
# LDA uses labels to maximize class separability

Truncated SVD (희소 데이터용)

TruncatedSVD(텍스트에서는 LSA라고도 함)가 희소 데이터용 PCA 대안입니다 — 데이터를 중심화하지 않아 TF-IDF 같은 희소 행렬에서 동작합니다. TF-IDF와 결합하면 '토픽' — 함께 나타나는 단어들의 그룹 — 을 만듭니다. 더 나은 토픽 모델링에는 NMF나 현대 임베딩 기반 접근을 시도하세요. 텍스트에는 약 100-300개 컴포넌트를 유지하세요; 올바른 수는 코퍼스 크기와 하류 작업에 달렸습니다.

machine-learning
from sklearn.decomposition import TruncatedSVD

# PCA doesn't work on sparse matrices (it needs to center data)
# Use TruncatedSVD instead — works directly on sparse TF-IDF, etc.

from scipy.sparse import csr_matrix
X_sparse = csr_matrix(X_tfidf)  # e.g. from TfidfVectorizer

svd = TruncatedSVD(n_components=100, random_state=42)
X_reduced = svd.fit_transform(X_sparse)

# Often combined with TF-IDF for LSA (Latent Semantic Analysis)
from sklearn.feature_extraction.text import TfidfVectorizer
from sklearn.decomposition import TruncatedSVD

vectorizer = TfidfVectorizer(max_features=10000)
lsa = Pipeline([
    ("tfidf", vectorizer),
    ("svd",   TruncatedSVD(n_components=100, random_state=42)),
])
X_topics = lsa.fit_transform(documents)
10

모델 평가

교차 검증

교차 검증이 여러 train/test 분할에 걸쳐 평균해 견고한 성능 추정을 줍니다. StratifiedKFold가 분류에서 클래스 균형을 유지합니다(불균형 데이터에 필수). RepeatedStratifiedKFold가 다른 분할로 CV를 여러 번 실행합니다 — 더 높은 연산 비용으로 더 안정적인 추정. 모델 선택에는 단일 train/test 분할이 아니라 항상 CV를 쓰세요.

machine-learning
from sklearn.model_selection import (cross_val_score, cross_validate,
    StratifiedKFold, KFold, RepeatedStratifiedKFold)

# Basic 5-fold CV
scores = cross_val_score(model, X, y, cv=5, scoring="accuracy")
print(f"{scores.mean():.3f} +/- {scores.std():.3f}")

# Stratified (preserves class balance — use for classification)
cv = StratifiedKFold(n_splits=5, shuffle=True, random_state=42)
scores = cross_val_score(model, X, y, cv=cv, scoring="f1_macro")

# Multiple metrics at once
results = cross_validate(model, X, y, cv=cv,
    scoring=["accuracy", "f1_macro", "roc_auc_ovr"],
    return_train_score=True)
print(results["test_f1_macro"].mean())

# Repeated CV for more stable estimates
rcv = RepeatedStratifiedKFold(n_splits=5, n_repeats=3, random_state=42)

학습 곡선

학습 곡선이 학습과 검증 성능을 데이터셋 크기에 대해 그립니다 — 편향 vs 분산의 최고 진단 도구입니다. 높은 학습 점수와 낮은 검증 점수 사이의 큰 간격은 과적합입니다(데이터 추가, 정규화, 단순화). 둘 다 낮고 가까우면 과소적합입니다(더 복잡한 모델이나 특성 추가). 곡선이 오른쪽 끝에서도 개선 중이면 더 많은 데이터가 도움이 됩니다.

machine-learning
from sklearn.model_selection import learning_curve
import matplotlib.pyplot as plt

train_sizes, train_scores, val_scores = learning_curve(
    model, X, y,
    train_sizes=np.linspace(0.1, 1.0, 10),
    cv=5, scoring="accuracy", n_jobs=-1, random_state=42,
)

train_mean = train_scores.mean(axis=1)
val_mean   = val_scores.mean(axis=1)

plt.plot(train_sizes, train_mean, "o-", label="Train")
plt.plot(train_sizes, val_mean,   "o-", label="Validation")
plt.xlabel("Training samples"); plt.ylabel("Accuracy")
plt.legend(); plt.show()

# Diagnose:
# - High train, low val  -> overfitting (high variance) -> more data or regularize
# - Both low and close   -> underfitting (high bias) -> more complex model/features
# - Gap closing with data -> more data helps

검증 곡선 (하이퍼파라미터)

검증 곡선이 성능을 단일 하이퍼파라미터 값에 대해 그립니다 — 모델 동작 이해와 그리드 검색 전 합리적 범위 찾기에 유용합니다. 학습 점수는 모델 복잡도와 함께 계속 오르지만 검증 점수는 정점에 찍힌 뒤 떨어집니다. 정점이 스위트 스팟이고, 그 전이 과소적합, 뒤가 과적합입니다.

machine-learning
from sklearn.model_selection import validation_curve
import matplotlib.pyplot as plt

param_range = [1, 2, 4, 8, 16, 32, 64]
train_scores, val_scores = validation_curve(
    RandomForestClassifier(random_state=42),
    X, y,
    param_name="max_depth",
    param_range=param_range,
    cv=5, scoring="accuracy", n_jobs=-1,
)

plt.plot(param_range, train_scores.mean(axis=1), "o-", label="Train")
plt.plot(param_range, val_scores.mean(axis=1),   "o-", label="Validation")
plt.xlabel("max_depth"); plt.ylabel("Accuracy")
plt.legend(); plt.show()

# Sweet spot is where validation peaks before overfitting

분류 리포트 해석

classification_report의 macro 평균은 모든 클래스를 동등하게 다룹니다(희귀 클래스가 중요할 때 좋습니다); weighted 평균은 클래스 빈도를 반영합니다(다수 클래스 성능이 지배할 때 좋습니다). 평균화 전략은 각 클래스를 놓치는 비즈니스 비용에 따라 고르세요. 심한 불균형에서는 PR-AUC와 클래스별 재현율을 보강하세요 — 정확도와 F1조차 다수 클래스만 예측하는 모델을 가릴 수 있습니다.

machine-learning
from sklearn.metrics import classification_report

report = classification_report(y_test, y_pred, output_dict=True)

# Per-class metrics + macro/weighted averages
import pandas as pd
df_report = pd.DataFrame(report).T
print(df_report[["precision", "recall", "f1-score", "support"]])

# 'macro' avg     = unweighted mean across classes (treats all equally)
# 'weighted' avg  = support-weighted mean (reflects class imbalance)
# Focus on:
# - macro F1 if all classes matter equally (e.g. digit recognition)
# - weighted F1 if rare classes matter less
# - recall of the positive class if it's the costly one (fraud, disease)

# For imbalanced classification, also report:
# - Precision-Recall AUC
# - Brier score (probability calibration)

회귀 지표 심화

회귀 지표는 비즈니스 비용에 따라 고르세요. 큰 오류가 과도하게 나쁘면 RMSE(제곱 패널티), 같은 크기의 모든 오류가 똑같이 나쁘면 MAE. R2는 단위 없이 데이터셋 간 비교 가능합니다. Max error가 최악의 사례를 보여줍니다. 커스텀 비대칭 손실(예: 과소 예측에 더 큰 패널티)이 실제 비용에 맞습니다: 품절 비용과 재고 과잉 비용은 다릅니다.

machine-learning
from sklearn.metrics import (mean_squared_error, mean_absolute_error,
    r2_score, explained_variance_score, max_error)

# RMSE — penalizes large errors; same units as y
rmse = mean_squared_error(y_test, y_pred, squared=False)

# MAE — robust to outliers; same units as y
mae = mean_absolute_error(y_test, y_pred)

# R^2 — fraction of variance explained (1.0 = perfect, 0 = predict mean)
r2 = r2_score(y_test, y_pred)

# Explained variance — like R^2 but ignores mean offset
evs = explained_variance_score(y_test, y_pred)

# Max error — single largest absolute error (worst-case)
max_err = max_error(y_test, y_pred)

# Custom asymmetric loss: penalize under-prediction more
def asymmetric_error(y_true, y_pred, under_penalty=2.0):
    error = y_true - y_pred
    return np.where(error > 0, under_penalty * error**2, error**2).mean()
11

교차 검증 전략

K-Fold 변형

올바른 CV 전략 선택이 결정적입니다. KFold가 기본입니다. 분류에는 StratifiedKFold(클래스 균형 유지). 샘플이 상관되어 있으면(사용자/환자당 여러 행) GroupKFold — train과 val 사이 정보 누출을 막습니다. 시간 데이터에는 TimeSeriesSplit(항상 과거로 학습, 미래로 검증). 잘못된 CV 전략은 낙관적인 추정을 줍니다.

machine-learning
from sklearn.model_selection import (KFold, StratifiedKFold,
    GroupKFold, TimeSeriesSplit, RepeatedKFold)

# Standard K-fold (regression or balanced classification)
kf = KFold(n_splits=5, shuffle=True, random_state=42)

# Stratified (classification — preserves class proportions)
skf = StratifiedKFold(n_splits=5, shuffle=True, random_state=42)

# Group K-fold (when samples are not independent — e.g. multiple rows per patient)
gkf = GroupKFold(n_splits=5)  # pass groups=patient_ids to CV

# Time series split (no shuffle — preserves temporal order)
tscv = TimeSeriesSplit(n_splits=5)

# Use with cross_val_score:
scores = cross_val_score(model, X, y, cv=gkf, groups=groups, scoring="f1")

시계열 교차 검증

TimeSeriesSplit이 시간 순서를 존중합니다: 각 폴드가 과거로 학습하고 미래로 검증하며, 그 반대는 절대 없습니다. 실제 예측 상황과 일치하고 누출을 막습니다. 인접 샘플이 자기상관되어 있으면(예: 내일의 가격이 오늘과 상관) gap 매개변수를 쓰세요. 시계열 데이터에 표준 셔플 KFold를 쓰면 극도로 낙관적인 추정이 나옵니다 — 초보자의 흔한 실수입니다.

machine-learning
from sklearn.model_selection import TimeSeriesSplit
import matplotlib.pyplot as plt
import numpy as np

tscv = TimeSeriesSplit(n_splits=5, test_size=100)
# gap parameter (sklearn 1.0+): prevent leakage from train to test
tscv = TimeSeriesSplit(n_splits=5, test_size=100, gap=10)

for fold, (train_idx, test_idx) in enumerate(tscv.split(X)):
    X_tr, X_te = X[train_idx], X[test_idx]
    y_tr, y_te = y[train_idx], y[test_idx]
    model.fit(X_tr, y_tr)
    score = model.score(X_te, y_te)
    print(f"Fold {fold}: train={len(train_idx)}, test={len(test_idx)}, score={score:.3f}")

# NEVER shuffle time-series data for CV — that leaks future into past
# Use gap to avoid leakage from autocorrelated near-future points

그룹 인식 CV

데이터에 그룹이 있으면(환자, 사용자, 세션당 여러 샘플) 표준 무작위 분할이 정보를 새어 나가게 합니다 — 모델이 train과 test에서 같은 엔티티를 봐 점수가 부풀려집니다. GroupKFold가 모든 그룹을 하나의 폴드에 온전히 유지합니다. 전형적 시나리오: 의료 데이터(환자당 여러 스캔), 추천 시스템(사용자당 여러 평점), 이미지 데이터(장면당 여러 프레임). 그룹 인식 CV를 안 쓰는 것은 ML의 가장 흔한 무소식 버그 중 하나입니다.

machine-learning
from sklearn.model_selection import GroupKFold, GroupShuffleSplit

# When the same entity appears in multiple rows (e.g. multiple X-rays per patient),
# random splits leak: the model memorizes patient-specific features
# instead of learning generalizable patterns.

# Solution: keep all rows of a group in the same split
gkf = GroupKFold(n_splits=5)
scores = cross_val_score(model, X, y, cv=gkf, groups=df["patient_id"])

# GroupShuffleSplit: random train/test split respecting groups
gss = GroupShuffleSplit(n_splits=5, test_size=0.2, random_state=42)
for train_idx, test_idx in gss.split(X, groups=df["patient_id"]):
    ...

# Always pass the groups argument to CV functions
# Common scenarios: patients, users, sessions, image batches

중첩 CV (편향 없는 하이퍼파라미터 튜닝)

표준 GridSearchCV의 보고된 CV 점수는 낙관적입니다 — 점수 매기는 데 쓴 같은 폴드로 최적 하이퍼파라미터를 골랐기 때문입니다. 중첩 CV가 이를 고칩니다: 바깥 CV 루프가 전체 튜닝 절차를 진짜 분리된 폴드에서 평가합니다. 결과는 완전한 모델링 파이프라인(튜닝 포함)이 새 데이터에서 어떻게 동작할지의 편향 없는 추정입니다. 정직한 벤치마킹, 특히 모델 비교에 쓰세요.

machine-learning
from sklearn.model_selection import (GridSearchCV, cross_val_score,
    StratifiedKFold)

# Outer loop: estimate generalization performance
# Inner loop: tune hyperparameters
# Without nesting, GridSearchCV's CV score is optimistic (it selected the best
# hyperparameters using the same data)

inner_cv = StratifiedKFold(n_splits=3, shuffle=True, random_state=42)
outer_cv = StratifiedKFold(n_splits=5, shuffle=True, random_state=42)

grid = GridSearchCV(
    RandomForestClassifier(random_state=42),
    param_grid={"max_depth": [3, 5, 10], "n_estimators": [50, 100]},
    cv=inner_cv, scoring="f1", n_jobs=-1,
)

nested_scores = cross_val_score(grid, X, y, cv=outer_cv, scoring="f1")
print(f"Nested CV F1: {nested_scores.mean():.3f} +/- {nested_scores.std():.3f}")

# Fit the final model on all data
grid.fit(X, y)
best_model = grid.best_estimator_

전처리와 CV (Pipeline)

전처리는 학습 폴드에만 fit되어야 합니다 — 아니면 테스트 폴드 통계(평균, 중앙값, 스케일링 인자)가 학습에 새어 CV 점수가 낙관적으로 됩니다. 해법은 모든 것을 Pipeline으로 감싸는 것입니다: scikit-learn이 각 CV 폴드가 학습 부분에 자기 전처리를 fit하도록 보장합니다. 정직한 ML 평가의 가장 중요한 모범 사례입니다. CV 전에 전체 데이터셋에 전처리를 fit하지 마세요.

machine-learning
from sklearn.pipeline import Pipeline
from sklearn.preprocessing import StandardScaler
from sklearn.model_selection import cross_val_score
from sklearn.impute import SimpleImputer

# RIGHT: wrap preprocessing in a Pipeline so each fold fits
# its own scaler/imputer on the training portion only
pipe = Pipeline([
    ("impute",  SimpleImputer(strategy="median")),
    ("scale",   StandardScaler()),
    ("model",   RandomForestClassifier(random_state=42)),
])

scores = cross_val_score(pipe, X, y, cv=5, scoring="f1")

# WRONG: fit scaler on the whole dataset, then CV
# (leaks test-fold statistics into training)
# scaler.fit(X)              # NO - includes future test folds
# X_scaled = scaler.transform(X)
# cross_val_score(model, X_scaled, y, cv=5)  # optimistic scores

# Pipelines also make deployment easier (one object, no leakage)
12

하이퍼파라미터 튜닝

그리드 검색

GridSearchCV가 모든 조합을 철저히 평가합니다 — thorough하지만 비쌉니다(조합 폭발). 작고 잘 고른 매개변수 그리드가 있을 때 쓰세요. 항상 적절한 scoring 지표를 전달하세요(기본은 accuracy로, 불균형 분류에서는 틀립니다). refit=True가 최선 모델을 전체 학습 데이터로 재학습해 반환된 추정기가 바로 쓸 수 있게 합니다.

machine-learning
from sklearn.model_selection import GridSearchCV

# Exhaustive search over all combinations
param_grid = {
    "n_estimators": [50, 100, 200],
    "max_depth":    [3, 5, 10, None],
    "min_samples_leaf": [1, 5, 10],
}
# 3 * 4 * 3 = 36 combinations, * 5 folds = 180 fits

grid = GridSearchCV(
    RandomForestClassifier(random_state=42),
    param_grid=param_grid,
    cv=5,
    scoring="f1",
    n_jobs=-1,
    refit=True,         # refit best model on full data
    return_train_score=True,
)
grid.fit(X_train, y_train)

print("Best params: ", grid.best_params_)
print("Best CV F1:  ", grid.best_score_)
best_model = grid.best_estimator_

무작위 검색

RandomizedSearchCV가 분포에서 n_iter 조합을 샘플링합니다 — 많은 매개변수가 관여할 때 그리드 검색보다 훨씬 효율적입니다. 학습률과 정규화 강도에는 loguniform을 쓰세요(몇 자릿수에 걸칩니다). 50-100회 반복이 보통 근접 최적 구성을 찾습니다. 무작위성이 그리드 검색이 놓칠 수 있는 국소 최적점 탈출에도 도움됩니다.

machine-learning
from sklearn.model_selection import RandomizedSearchCV
from scipy.stats import randint, loguniform

# Sample from distributions instead of enumerating all combos
# Much more efficient when the grid is large
param_dist = {
    "n_estimators":     randint(50, 500),     # discrete uniform
    "max_depth":        [3, 5, 10, None],
    "min_samples_leaf": randint(1, 20),
    "learning_rate":    loguniform(1e-3, 1e0),  # log-uniform
}

rand_search = RandomizedSearchCV(
    GradientBoostingClassifier(random_state=42),
    param_distributions=param_dist,
    n_iter=50,           # number of parameter settings sampled
    cv=5,
    scoring="f1",
    n_jobs=-1,
    random_state=42,
)
rand_search.fit(X_train, y_train)
print("Best params:", rand_search.best_params_)

베이지안 최적화 (Optuna)

Optuna가 이전 시도 결과를 기반으로 다음 하이퍼파라미터를 지능적으로 샘플링합니다 — 그리드/무작위 검색보다 훨씬 샘플 효율적입니다. 가지치기(나쁜 시도의 조기 중단), 조건부 매개변수 공간, 다목적 최적화도 지원합니다. study 객체가 모든 시도를 저장해 매개변수 중요도와 최적화 히스토리를 시각화할 수 있습니다. 하이퍼파라미터가 많고 비싼 모델에 최선입니다.

machine-learning
import optuna

def objective(trial):
    # Suggest hyperparameters
    n_estimators = trial.suggest_int("n_estimators", 50, 500)
    max_depth    = trial.suggest_int("max_depth", 3, 20)
    lr           = trial.suggest_float("learning_rate", 1e-3, 1e0, log=True)
    min_samples  = trial.suggest_int("min_samples_leaf", 1, 20)

    model = GradientBoostingClassifier(
        n_estimators=n_estimators, max_depth=max_depth,
        learning_rate=lr, min_samples_leaf=min_samples,
        random_state=42,
    )
    # 5-fold CV F1
    score = cross_val_score(model, X_train, y_train, cv=5,
                            scoring="f1", n_jobs=-1).mean()
    return score  # Optuna maximizes by default

study = optuna.create_study(direction="maximize")
study.optimize(objective, n_trials=100, timeout=600)

print("Best trial:", study.best_trial.params)
print("Best F1:    ", study.best_trial.value)

Halving 검색 (연속 절반)

halving 검색은 반복적 리소스 할당 전략입니다: 적은 데이터로 많은 후보를 평가한 뒤 최악을 제거하고 남은 것을 더 많은 데이터(또는 추정기)로 재평가합니다. 전체 그리드 검색보다 훨씬 빠르며 비슷한 해를 찾는 경우가 많습니다. 더 큰 공간에는 HalvingRandomSearchCV를 쓰세요. 'factor'가 후보를 얼마나 공격적으로 제거할지 제어합니다. 하이퍼파라미터가 많고 시간이 제한될 때 훌륭한 기본값입니다.

machine-learning
from sklearn.experimental import enable_halving_search_cv  # noqa
from sklearn.model_selection import HalvingGridSearchCV, HalvingRandomSearchCV

# Allocate more resources to promising candidates iteratively
halving = HalvingGridSearchCV(
    RandomForestClassifier(random_state=42),
    param_grid={"max_depth": [3, 5, 10, None],
                "n_estimators": [50, 100, 200]},
    cv=5,
    scoring="f1",
    factor=3,           # eliminate bottom 2/3 each round
    aggressive_elimination=False,
    n_jobs=-1,
)
halving.fit(X_train, y_train)
print("Best params:", halving.best_params_)
print("Best score: ", halving.best_score_)

# Much faster than full GridSearchCV — evaluates many candidates
# cheaply first, then invests more resources in the promising ones.

튜닝 모범 사례

가장 큰 튜닝 죄: 테스트 셋에서 최적화, 검증 셋에 과적합될 때까지 튜닝, CV 점수를 최종 성능으로 보고. 학습 데이터의 CV로 튜닝한 뒤 최종 모델은 깨끗하게 분리된 테스트 셋에서 한 번만 평가하세요. 선택된 하이퍼파라미터가 견고한지(폴드 간 작은 std) 단순히 운 좋은 무작위 시드가 아닌지 확인하려 전체 cv_results_를 검사하세요. 거칠게 시작해 정밀화하세요 — 대부분의 이득은 소수의 핵심 매개변수에서 옵니다.

machine-learning
# 1. Tune on a VALIDATION set or via CV — never on the test set
# 2. Use the metric you actually care about (scoring=...)
# 3. Set random_state for reproducibility
# 4. Start coarse (randomized, few iterations), then refine around the best
# 5. Don't over-tune — small improvements may be noise

# Inspect full results to understand hyperparameter sensitivity
import pandas as pd
results = pd.DataFrame(grid.cv_results_)
cols = ["param_max_depth", "param_n_estimators",
        "mean_test_score", "std_test_score", "rank_test_score"]
print(results[cols].sort_values("rank_test_score").head(10))

# Refit the best model on the FULL training set (automatic with refit=True)
# Then evaluate ONCE on the held-out test set
test_score = grid.best_estimator_.score(X_test, y_test)
print(f"Test score: {test_score:.3f}")
13

앙상블 학습

Bagging (부트스트랩 집계)

bagging이 부트스트랩 샘플(복원 추출)로 많은 모델을 학습하고 예측을 평균합니다 — 편향을 늘리지 않고 분산을 줄입니다. Random Forest가 분할마다 특성 무작위성을 더해 더 다양한 트리를 만듭니다. Out-of-Bag(OOB) 점수가 각 트리가 학습하지 않은 약 37% 샘플로 트리를 평가합니다 — 별도 셋 없이 공짜 검증 추정입니다. 검증 셋을 뗄 수 없는 작은 데이터셋에 OOB가 좋습니다.

machine-learning
from sklearn.ensemble import BaggingClassifier, RandomForestClassifier

# Bagging: train multiple models on bootstrap samples (with replacement)
bag = BaggingClassifier(
    estimator=DecisionTreeClassifier(),  # any base estimator
    n_estimators=100,
    max_samples=1.0,         # fraction of samples per bootstrap
    max_features=1.0,        # fraction of features per estimator
    bootstrap=True,
    n_jobs=-1,
    random_state=42,
)
bag.fit(X_train, y_train)

# Random Forest is bagging + random feature subsets at each split
# Out-of-bag (OOB) score: evaluate each tree on samples it didn't see
rf = RandomForestClassifier(n_estimators=200, oob_score=True,
                             random_state=42)
rf.fit(X_train, y_train)
print("OOB score:", rf.oob_score_)  # ~ validation accuracy for free

Boosting

boosting이 모델을 순차 학습해 각각이 이전의 오류를 교정합니다 — 편향을(그리고 약간의 분산을) 줄입니다. AdaBoost가 샘플을 재가중하고, 그라디언트 부스팅이 잔차를 직접 fit합니다. learning_rate와 n_estimators가 트레이드오프입니다: 낮은 learning_rate는 더 많은 추정기를 필요로 하지만 보통 더 잘 일반화합니다 — 항상 조기 중단을 쓰세요. HistGradientBoosting이 sklearn의 빠른 히스토그램 구현으로 LightGBM에 필적합니다.

machine-learning
from sklearn.ensemble import (AdaBoostClassifier,
    GradientBoostingClassifier, HistGradientBoostingClassifier)

# AdaBoost: weight misclassified samples higher each round
ada = AdaBoostClassifier(
    estimator=DecisionTreeClassifier(max_depth=1),
    n_estimators=200, learning_rate=0.5, random_state=42,
)
ada.fit(X_train, y_train)

# Gradient Boosting: fit each new tree to the residuals of the previous
gb = GradientBoostingClassifier(
    n_estimators=200, learning_rate=0.1, max_depth=3,
    subsample=0.8,        # stochastic GB — adds randomness
    random_state=42,
)
gb.fit(X_train, y_train)

# HistGradientBoosting: faster, native NaN handling, large-data friendly
hgb = HistGradientBoostingClassifier(
    max_iter=200, learning_rate=0.1, max_leaf_nodes=31,
    l2_regularization=0.0, early_stopping=True,
    random_state=42,
)
hgb.fit(X_train, y_train)

Stacking (메타 학습)

voting 앙상블이 다양한 모델의 예측을 평균합니다 — soft voting(확률)이 보통 hard voting(다수결)을 이깁니다. stacking이 더 나아갑니다: 메타 모델이 기저 모델들의 예측을 최적으로 결합하는 법을 학습해 추가 성능을 짜내는 경우가 많습니다. 메타 모델은 누출을 피하려 기저 모델의 out-of-fold 예측으로 학습됩니다(cv로 설정). 가장 큰 이득을 위해 다양한 기저 모델(서로 다른 알고리즘)을 쓰세요 — 랜덤 포레스트 셋을 결합하는 건 무의미합니다.

machine-learning
from sklearn.ensemble import StackingClassifier, VotingClassifier
from sklearn.linear_model import LogisticRegression
from sklearn.svm import SVC

# Voting: simple average of predictions (hard=majority, soft=probabilities)
voting = VotingClassifier(
    estimators=[
        ("rf",  RandomForestClassifier(n_estimators=100, random_state=42)),
        ("svc", SVC(probability=True, random_state=42)),
        ("lr",  LogisticRegression(max_iter=1000)),
    ],
    voting="soft",     # use predict_proba
    weights=[2, 1, 1], # weight each model
)

# Stacking: train a meta-model on base model predictions
stacking = StackingClassifier(
    estimators=[
        ("rf",  RandomForestClassifier(n_estimators=100, random_state=42)),
        ("svc", SVC(probability=True, random_state=42)),
        ("lr",  LogisticRegression(max_iter=1000)),
    ],
    final_estimator=LogisticRegression(),  # meta-model
    cv=5,            # use CV predictions to train meta-model (avoids leakage)
    n_jobs=-1,
)
stacking.fit(X_train, y_train)

Voting vs Stacking vs Blending

세 앙상블 전략 모두 다양한 모델을 결합하며 정교함이 올라갑니다: voting(가장 단순, 평균), blending(홀드아웃 셋의 메타 모델), stacking(CV 예측의 메타 모델, 더 견고). 실전에서는 stacking이 선호됩니다 — CV 기반 메타 특성이 모든 학습 데이터를 쓰고 분산을 줄입니다. blending은 더 단순하고 빠르지만 메타 모델에 더 적은 데이터를 씁니다. 모두 가치를 더하려 다양한 기저 모델이 필요합니다.

machine-learning
# Voting:  simple average of predictions
# Stacking: meta-model trained on CV predictions of base models
# Blending: like stacking but meta-model trained on a single holdout set

# Blending (manual implementation):
# 1. Split train into train' and holdout
# 2. Train base models on train'
# 3. Get predictions on holdout
# 4. Train meta-model on (holdout_predictions, holdout_y)
# 5. Retrain base models on full train for final ensemble

from sklearn.model_selection import train_test_split
X_tr, X_hold, y_tr, y_hold = train_test_split(X_train, y_train, test_size=0.3,
                                               random_state=42)

# Train base models on X_tr
rf.fit(X_tr, y_tr); svc.fit(X_tr, y_tr); lr.fit(X_tr, y_tr)

# Get holdout predictions as new features
import numpy as np
holdout_preds = np.column_stack([
    rf.predict_proba(X_hold)[:, 1],
    svc.predict_proba(X_hold)[:, 1],
    lr.predict_proba(X_hold)[:, 1],
])
meta_model = LogisticRegression().fit(holdout_preds, y_hold)

다양성 & 상관

앙상블이 구성원을 이기려 모델들이 상관되지 않은 오류를 만들어야 합니다. 세 모델이 같은 실수를 하면 앙상블도 그렇게 합니다. 예측 상관을 측정하세요 — 낮을수록 좋습니다. 다양성은 알고리즘 계열(트리, 선형, 거리 기반) 혼합, 다른 특성 부분집합 학습, 다른 하이퍼파라미터 레짐 사용으로 높이세요. 같은 알고리즘-다른 시드 다양성은 약하고, 알고리즘 다양성이 강합니다.

machine-learning
import numpy as np
from scipy.stats import spearmanr

# An ensemble only helps if models make DIFFERENT errors
# Measure prediction correlation between base models
preds = np.column_stack([rf.predict_proba(X_test)[:, 1],
                          svc.predict_proba(X_test)[:, 1],
                          lr.predict_proba(X_test)[:, 1]])
corr = spearmanr(preds).correlation
print("Prediction correlation matrix:")
print(corr)

# Low correlation = diverse models = better ensemble
# High correlation = redundant models = no benefit

# Ways to encourage diversity:
# 1. Different algorithms (tree + linear + nearest-neighbor)
# 2. Different feature subsets
# 3. Different hyperparameters
# 4. Different training samples (bagging)
# 5. Different random seeds (weakest form of diversity)
14

딥러닝 기본

PyTorch 텐서 & Autograd

PyTorch 텐서는 자동 미분을 위해 그라디언트를 추적하는 numpy류 배열입니다. requires_grad=True가 텐서에 autograd를 켜고, 스칼라에 .backward()를 호출하면 모든 상류 텐서의 그라디언트가 계산됩니다. 가속을 위해 .to(device)로 텐서를 GPU로 옮기세요. .detach()가 텐서를 그라디언트 그래프에서 떼어냅니다(로깅이나 numpy 변환용).

machine-learning
import torch

# Tensors: like numpy arrays but on GPU and with autograd
x = torch.randn(3, 4, requires_grad=True)
y = torch.randn(4, 2, requires_grad=True)
z = x @ y               # matrix multiply
loss = z.sum()

# Automatic differentiation
loss.backward()         # populate .grad
print(x.grad.shape)     # torch.Size([3, 4])
print(y.grad.shape)     # torch.Size([4, 2])

# Move to GPU
device = torch.device("cuda" if torch.cuda.is_available() else "cpu")
x = x.to(device)

# Detach from graph (e.g. for logging)
numpy_array = z.detach().cpu().numpy()

학습 루프 해부

모든 PyTorch 학습 루프가 같은 구조입니다: zero_grad, forward, loss, backward, step. model.train() / model.eval()이 dropout과 batchnorm 동작을 토글합니다 — 전환을 잊으면 무소식 버그입니다. torch.no_grad()가 추론용 그라디언트 추적을 끕니다(메모리와 연산 절약). 배치는 항상 모델과 같은 디바이스로 옮기세요. dataloader가 배칭과 셔플링을 처리하고 루프는 그저 순회합니다.

machine-learning
import torch
import torch.nn as nn
import torch.optim as optim

model = nn.Sequential(
    nn.Linear(784, 128), nn.ReLU(),
    nn.Linear(128, 64),  nn.ReLU(),
    nn.Linear(64, 10),
).to(device)

criterion = nn.CrossEntropyLoss()
optimizer = optim.Adam(model.parameters(), lr=1e-3)

for epoch in range(epochs):
    model.train()                            # enable dropout/batchnorm
    for X_batch, y_batch in train_loader:
        X_batch, y_batch = X_batch.to(device), y_batch.to(device)

        optimizer.zero_grad()                # clear old gradients
        logits = model(X_batch)              # forward
        loss = criterion(logits, y_batch)    # compute loss
        loss.backward()                      # backprop
        optimizer.step()                     # update weights

    # Validation
    model.eval()                             # disable dropout/batchnorm
    with torch.no_grad():                    # no gradient tracking
        val_loss, correct = 0, 0
        for X_batch, y_batch in val_loader:
            logits = model(X_batch.to(device))
            val_loss += criterion(logits, y_batch.to(device))
            correct += (logits.argmax(1).cpu() == y_batch).sum().item()
    print(f"Epoch {epoch}: val_loss={val_loss/len(val_loader):.4f}, "
          f"val_acc={correct/len(val_loader.dataset):.4f}")

흔한 레이어

Linear + ReLU가 기본 숨은 레이어입니다. 이미지에는 Conv2d + MaxPool; 짧은 시퀀스에는 LSTM/GRU; 긴 시퀀스나 텍스트에는 Transformer. BatchNorm이 학습을 안정화하고, Dropout이 정규화합니다. 주의: PyTorch의 CrossEntropyLoss가 이미 log-softmax를 적용하므로 분류 모델 끝에 Softmax 레이어를 더하지 마세요 — raw 로짓을 출력하세요.

machine-learning
import torch.nn as nn

# Linear (fully connected)
nn.Linear(in_features=128, out_features=64)

# Activations
nn.ReLU()        # default for hidden layers
nn.GELU()        # smoother, used in transformers
nn.Sigmoid()     # outputs in (0, 1)
nn.Softmax(dim=1)# multi-class probabilities (built into CrossEntropyLoss)

# Convolution (images)
nn.Conv2d(in_channels=3, out_channels=32, kernel_size=3, padding=1)
nn.MaxPool2d(kernel_size=2)   # downsample by 2
nn.BatchNorm2d(32)            # stabilize training
nn.Dropout(p=0.5)             # regularization

# Recurrent (sequences)
nn.LSTM(input_size=64, hidden_size=128, num_layers=2, batch_first=True)

# Transformer (attention)
nn.TransformerEncoderLayer(d_model=512, nhead=8, batch_first=True)

옵티마이저

Adam이 가장 인기 있는 옵티마이저입니다 — 매개변수별 적응형 학습률, 빠른 수렴, 최소 튜닝. AdamW가 Adam의 weight-decay 버그를 고쳐 트랜스포머에 선호됩니다. momentum이 있는 SGD는 CNN에서 더 잘 일반화할 수 있지만 튜닝이 더 필요합니다. 학습률 스케줄러(cosine annealing, one-cycle)가 흔히 공짜로 1-2% 정확도를 더합니다. 학습률이 가장 중요한 하이퍼파라미터입니다 — 항상 먼저 튜닝하세요.

machine-learning
import torch.optim as optim

# SGD with momentum — robust default
optim.SGD(model.parameters(), lr=0.01, momentum=0.9, weight_decay=1e-4)

# Adam — adaptive, often faster convergence
optim.Adam(model.parameters(), lr=1e-3, weight_decay=1e-4)

# AdamW — proper weight decay (preferred over Adam for transformers)
optim.AdamW(model.parameters(), lr=1e-3, weight_decay=0.01)

# Learning rate scheduler — reduce LR over training
from torch.optim.lr_scheduler import CosineAnnealingLR, OneCycleLR
scheduler = CosineAnnealingLR(optimizer, T_max=epochs)
# or OneCycleLR for super-convergence (needs careful setup)

# In training loop:
optimizer.step()
scheduler.step()  # update LR each epoch (or batch for OneCycleLR)

과적합 & 정규화

과적합: 학습 손실은 계속 떨어지는데 검증 손실은 오릅니다. Dropout이 학습 중 유닛을 무작위 비활성화해 중복성을 강제합니다. Weight decay(L2)가 가중치를 0 쪽으로 줄입니다. 조기 중단이 검증 손실을 감시하다 정체되면 멈춥니다 — 항상 최선 체크포인트를 저장하세요. 데이터 증강이 이미지/텍스트의 가장 강한 정규화기입니다. 다른 방법이 실패하면 모델 용량 축소가 가장 단순한 해법입니다.

machine-learning
# 1. Dropout — randomly zero out units during training
nn.Dropout(p=0.5)

# 2. Weight decay (L2 regularization) via optimizer
optim.AdamW(model.parameters(), lr=1e-3, weight_decay=0.01)

# 3. Early stopping — stop when validation loss stops improving
best_val, patience, counter = float("inf"), 5, 0
for epoch in range(epochs):
    val_loss = validate(model, val_loader)
    if val_loss < best_val:
        best_val, counter = val_loss, 0
        torch.save(model.state_dict(), "best.pt")  # save best
    else:
        counter += 1
        if counter >= patience:
            print("Early stopping at epoch", epoch)
            break

# 4. Data augmentation (especially for images/text)
# 5. Batch normalization (mild regularizing effect)
# 6. Reduce model capacity (fewer layers/units)
15

평가 지표 심화

정밀도, 재현율 & F1

정밀도와 재현율이 거짓 양성과 거짓 음성의 트레이드오프를 담습니다. 비즈니스 비용에 따라 고르세요: 스팸에는 정밀도(거짓 양성 = 중요한 이메일 손실), 암 검진에는 재현율(거짓 음성 = 진단 놓침). F1이 둘을 균등하게 균형 잡고, F-beta가 기울일 수 있게 합니다 — F2는 재현율을 두 배, F0.5는 정밀도를 두 배 가중합니다. F1만이 아니라 항상 정밀도와 재현율 둘 다 보고하세요.

machine-learning
from sklearn.metrics import (precision_score, recall_score,
    f1_score, fbeta_score)

# Precision: TP / (TP + FP) — of predicted positives, how many are real
# Recall:    TP / (TP + FN) — of actual positives, how many we caught
# F1:        harmonic mean of precision and recall
# F-beta:    weighted (beta > 1 favors recall, < 1 favors precision)

precision = precision_score(y_test, y_pred)
recall    = recall_score(y_test, y_pred)
f1        = f1_score(y_test, y_pred)
f2        = fbeta_score(y_test, y_pred, beta=2.0)   # recall-weighted
f05       = fbeta_score(y_test, y_pred, beta=0.5)   # precision-weighted

# When to use which:
# - Precision matters when false positives are costly (spam filter)
# - Recall matters when false negatives are costly (cancer screening)
# - F2 when recall is more important; F0.5 when precision is more important

ROC-AUC & PR-AUC

ROC-AUC가 모델이 양성을 음성보다 얼마나 잘 순위 매기는지 측정합니다 — 임계값 독립적이라 유용합니다. PR-AUC(average_precision_score)가 정밀도-재현율 곡선의 아래 면적이며 불균형 데이터에서 더 정보적입니다(ROC-AUC가 훌륭해 보여도 PR-AUC가 형편없을 수 있습니다). 다중 클래스에서는 'ovr'(one-vs-rest)과 'ovo'(one-vs-one)가 AUC를 다르게 계산합니다; 확실치 않으면 둘 다 보고하세요. 운영 임계값 선택에는 Youden's J를 쓰세요.

machine-learning
from sklearn.metrics import (roc_auc_score, average_precision_score,
    roc_curve, precision_recall_curve)

# ROC-AUC: probability that model ranks a random positive
#          above a random negative. Threshold-independent.
roc_auc = roc_auc_score(y_test, y_proba)

# PR-AUC (average precision): area under precision-recall curve.
# More informative than ROC-AUC on imbalanced data.
pr_auc = average_precision_score(y_test, y_proba)

# Multiclass ROC-AUC
roc_auc_ovr = roc_auc_score(y_test, y_proba_multi,
                            multi_class="ovr", average="macro")
roc_auc_ovo = roc_auc_score(y_test, y_proba_multi,
                            multi_class="ovo", average="macro")

# Find the optimal threshold (Youden's J = TPR - FPR)
fpr, tpr, thresholds = roc_curve(y_test, y_proba)
j_scores = tpr - fpr
best_threshold = thresholds[j_scores.argmax()]

혼동 행렬 시각화

집계 지표만이 아니라 항상 혼동 행렬을 시각화하세요 — 어떤 클래스들이 서로 혼동되는지 보여 모델의 약점을 드러냅니다(예: 숫자 분류기가 4와 9를 혼동). 행별(진짜 클래스)로 정규화하면 클래스별 재현율이 보입니다 — 클래스가 불균형일 때 중요합니다. ConfusionMatrixDisplay가 이를 한 줄로 만듭니다. 대각선 밖 셀에 실수가 집중됩니다.

machine-learning
from sklearn.metrics import (confusion_matrix,
    ConfusionMatrixDisplay)
import matplotlib.pyplot as plt

cm = confusion_matrix(y_test, y_pred)

# Display with sklearn
disp = ConfusionMatrixDisplay(confusion_matrix=cm,
                              display_labels=class_names)
fig, ax = plt.subplots(figsize=(8, 6))
disp.plot(cmap="Blues", ax=ax, values_format="d")  # or ".2%" for normalized
plt.title("Confusion matrix")
plt.show()

# Normalized per row (true class) — see per-class recall
cm_norm = cm.astype(float) / cm.sum(axis=1, keepdims=True)
disp = ConfusionMatrixDisplay(confusion_matrix=cm_norm,
                              display_labels=class_names)
disp.plot(cmap="Blues", values_format=".2%")

회귀 지표 요약

여러 지표를 보고하세요: 큰 오류에 민감한 RMSE, 전형적 오류의 MAE, 이상치에 강건한 median AE, 최악의 경우 SLA용 max error, 단위 없는 해석 가능성의 R2. 치우친 타깃(소득, 가격)에는 y를 로그 변환하고 로그 공간에서 지표를 보고하세요 — 이는 곱셈적 오류에 맞고 분산을 안정화합니다. 항상 산점도로 예측 vs 실측을 온전성 검사하세요.

machine-learning
from sklearn.metrics import (mean_squared_error, mean_absolute_error,
    r2_score, median_absolute_error, max_error,
    explained_variance_score, d2_tweedie_score)

# RMSE (penalizes large errors, same units as y)
rmse = mean_squared_error(y_test, y_pred, squared=False)

# MAE (robust to outliers, same units as y)
mae = mean_absolute_error(y_test, y_pred)

# Median AE (extremely robust to outliers)
med_ae = median_absolute_error(y_test, y_pred)

# Max error (worst single prediction — useful for SLAs)
max_err = max_error(y_test, y_pred)

# R^2 (1=perfect, 0=mean prediction, <0=worse than mean)
r2 = r2_score(y_test, y_pred)

# Explained variance (like R^2 but ignores bias)
evs = explained_variance_score(y_test, y_pred)

비즈니스 정렬 지표

ML 지표(정확도, F1, AUC)는 실제로 관심 있는 것 — 비즈니스 성과 — 의 대리물입니다. 비즈니스 비용을 커스텀 지표로 번역하세요: 사기 거짓 음성의 비용이 $X, 거짓 양성의 비용이 $Y, k순위 광고 클릭의 수익이 $Z. 대리물이 아니라 진짜 목표(이익, 구해진 생명, 예방된 이탈)로 최적화하세요. 커스텀 임계값 최적화가 추가 0.01 AUC를 짜내는 것보다 종종 더 많은 가치를 냅니다.

machine-learning
# Sometimes the right metric isn't in sklearn — define your own.

# Example 1: Cost matrix (asymmetric costs)
def cost_weighted_error(y_true, y_pred, cost_fp=1, cost_fn=10):
    cm = confusion_matrix(y_true, y_pred)
    tn, fp, fn, tp = cm.ravel()
    return (cost_fp * fp + cost_fn * fn) / len(y_true)

# Example 2: Profit at K (top-K precision weighted by revenue)
def profit_at_k(y_true, y_proba, revenue_per_hit, k=100):
    top_k_idx = np.argsort(y_proba)[::-1][:k]
    hits = y_true[top_k_idx].sum()
    return hits * revenue_per_hit - k * cost_per_contact

# Example 3: Custom threshold optimization
def optimize_threshold_for_profit(y_true, y_proba, profit_matrix):
    best_t, best_profit = 0.5, -float("inf")
    for t in np.linspace(0.01, 0.99, 99):
        y_pred = (y_proba >= t).astype(int)
        profit = profit_matrix(y_true, y_pred)
        if profit > best_profit:
            best_t, best_profit = t, profit
    return best_t, best_profit
16

파이프라인

기본 Pipeline

Pipeline이 전처리와 모델링을 단일 추정기로 체이닝해, CV 동안 전처리가 학습 폴드에만 fit되도록 보장합니다(누출 방지). 배포도 단순해집니다 — 별개의 scaler, imputer, 모델 대신 하나의 객체. 명확성을 위해 named step을 쓰세요. Pipeline이 정직하고 재현 가능한 ML의 가장 깔끔한 방법입니다 — 최적화가 아니라 기본값으로 삼으세요.

machine-learning
from sklearn.pipeline import Pipeline
from sklearn.preprocessing import StandardScaler
from sklearn.impute import SimpleImputer
from sklearn.ensemble import RandomForestClassifier

pipe = Pipeline([
    ("impute", SimpleImputer(strategy="median")),
    ("scale",  StandardScaler()),
    ("clf",    RandomForestClassifier(random_state=42)),
])

# Use like any estimator
pipe.fit(X_train, y_train)
y_pred = pipe.predict(X_test)
score = pipe.score(X_test, y_test)

# Access steps
pipe.named_steps["clf"]
pipe[:-1].get_feature_names_out()  # see transformed feature names

# Pipelines prevent leakage: each CV fold fits its own preprocessing

ColumnTransformer (이질적 데이터)

ColumnTransformer가 수치 컬럼과 범주형 컬럼에 다른 전처리를 적용합니다 — 실제 표 형식 데이터에 필수입니다. 각 서브 파이프라인이 자체 대체와 인코딩을 담당합니다. remainder='drop'이 나열되지 않은 컬럼을 버리고, 'passthrough'는 그대로 유지합니다. ColumnTransformer를 모델과 함께 Pipeline으로 감싸 이질적 전처리의 누출 없는 CV를 얻으세요. 이것이 표 형식 ML의 프로덕션 준비 패턴입니다.

machine-learning
from sklearn.compose import ColumnTransformer
from sklearn.preprocessing import (StandardScaler, OneHotEncoder)
from sklearn.pipeline import Pipeline
from sklearn.impute import SimpleImputer

numeric_features     = ["age", "income", "score"]
categorical_features = ["city", "occupation"]

# Different preprocessing for different column types
preprocessor = ColumnTransformer(
    transformers=[
        ("num", Pipeline([
            ("impute", SimpleImputer(strategy="median")),
            ("scale",  StandardScaler()),
        ]), numeric_features),
        ("cat", Pipeline([
            ("impute", SimpleImputer(strategy="most_frequent")),
            ("onehot", OneHotEncoder(handle_unknown="ignore")),
        ]), categorical_features),
    ],
    remainder="drop",  # or 'passthrough' to keep other columns
)

full_pipe = Pipeline([
    ("preprocess", preprocessor),
    ("clf", RandomForestClassifier(random_state=42)),
])
full_pipe.fit(X_train, y_train)

튜닝이 있는 Pipeline

Pipeline이 GridSearchCV와 아름답게 조합됩니다 — 'step__param' 문법으로 전처리와 모델 하이퍼파라미터를 함께 튜닝할 수 있습니다. 이는 이 모델에 최적인 전처리 조합을 찾는데, 격리된 최적 전처리와 흔히 다릅니다. 모델만이 아니라 항상 전체 파이프라인을 튜닝하세요. 결합 튜닝이 더 정직하고(전처리를 고르려고 테스트 데이터 들여다보기 없음) 더 나은 구성을 찾는 경우가 많습니다.

machine-learning
from sklearn.model_selection import GridSearchCV

# Reference nested parameters with 'step__param' syntax
param_grid = {
    "preprocess__num__impute__strategy": ["mean", "median"],
    "clf__n_estimators": [50, 100, 200],
    "clf__max_depth":    [3, 5, 10, None],
}

grid = GridSearchCV(full_pipe, param_grid, cv=5, scoring="f1", n_jobs=-1)
grid.fit(X_train, y_train)
print("Best params:", grid.best_params_)

# Tune preprocessing AND model together — finds the best combo
# e.g. median imputation + 100 trees + max_depth=10

커스텀 Transformer

커스텀 transformer가 도메인별 전처리(로그 변환, 날짜 특성 추출, 텍스트 정제)를 재사용 가능하고 파이프라인 호환인 컴포넌트로 캡슐화하게 합니다. BaseEstimator와 TransformerMixin을 상속하고 fit(보통 self 반환)과 transform을 구현하세요. 이로써 특성 공학이 버저닝되고, 테스트 가능하고, 누출 없이 유지됩니다 — 로직을 노트북 여기저기 흩뿌리는 것보다 훨씬 낫습니다. 일회성 함수에는 FunctionTransformer를 쓰세요.

machine-learning
from sklearn.base import BaseEstimator, TransformerMixin
import numpy as np

class LogTransformer(BaseEstimator, TransformerMixin):
    def __init__(self, columns=None):
        self.columns = columns

    def fit(self, X, y=None):
        return self  # nothing to fit

    def transform(self, X):
        X = X.copy()
        if self.columns is None:
            return np.log1p(X)
        X[self.columns] = np.log1p(X[self.columns])
        return X

# Use in a pipeline
pipe = Pipeline([
    ("log",  LogTransformer(columns=["income", "price"])),
    ("scale", StandardScaler()),
    ("clf",   LogisticRegression()),
])

# For more complex logic, use FunctionTransformer or write a full class

Pipeline 저장 & 로드

joblib(pickle이 아님)이 sklearn 파이프라인 직렬화의 표준입니다 — numpy 배열을 효율적으로 다루고 압축을 기본 지원합니다. 프로덕션에서는 sklearn 버전을 고정하세요: 한 버전에서 저장된 모델이 다른 버전에서 로드된다는 보장이 없습니다. 크로스 언어 배포(Java/Go에서 Python 모델 서빙)에는 skl2onnx로 ONNX로 변환하세요. 추론 시 전처리가 동일하도록 모델만이 아니라 항상 전체 파이프라인을 저장하세요.

machine-learning
import joblib

# Save the entire fitted pipeline
joblib.dump(full_pipe, "model.pkl")

# Later (e.g. in a web service)
loaded = joblib.load("model.pkl")
predictions = loaded.predict(new_data)

# Why joblib over pickle?
# - More efficient for numpy arrays (which sklearn models contain)
# - Handles objects with large numerical arrays via compression

# Version compatibility:
# - sklearn versions must match between save and load in production
# - Pin sklearn in requirements.txt: scikit-learn==1.4.2

# For cross-language deployment, use ONNX:
# import skl2onnx
# onx = skl2onnx.convert_sklearn(full_pipe, ...)
17

모델 영속화

joblib vs pickle

sklearn 모델에는 joblib을 쓰세요 — numpy 배열에 최적화되어 있고 압축을 기본 지원합니다. pickle은 임의 Python 객체의 폴백입니다. 둘 다 같은 보안 주의점이 있습니다: 신뢰할 수 없는 pickle/joblib 파일은 절대 로드하지 마세요 — 역직렬화 시 임의 코드를 실행할 수 있습니다. 신뢰할 수 없는 환경에 모델을 서빙하려면 ONNX나 입력 검증이 있는 모델 서버를 쓰세요.

machine-learning
import joblib
import pickle

# joblib — preferred for sklearn (efficient with numpy arrays)
joblib.dump(model, "model.joblib", compress=3)
model = joblib.load("model.joblib")

# pickle — standard library, works for any picklable object
with open("model.pkl", "wb") as f:
    pickle.dump(model, f)
with open("model.pkl", "rb") as f:
    model = pickle.load(f)

# Compress to save disk space (joblib supports it natively)
joblib.dump(model, "model.joblib", compress=("xz", 3))

# Load partially for inspection without full deserialize
# (advanced, not commonly needed)

모델 버저닝

모델을 항상 메타데이터로 버저닝하세요: 프레임워크 버전(sklearn, python), 특성 목록, 학습 데이터 해시, 지표, git commit, 타임스탬프. 이로써 프로덕션 문제 디버깅이 다뤄질 수 있게 됩니다 — 모델이 다르게 동작하면 메타데이터를 비교해 무엇이 바뀌었는지 볼 수 있습니다. 시맨틱 버저닝을 쓰세요: 재학습은 patch, 새 특성은 minor, 파괴적 변경은 major(옛 예측을 깨뜨리는 새 전처리).

machine-learning
# Save metadata alongside the model artifact
import joblib, json
from datetime import datetime

metadata = {
    "model_type": "RandomForestClassifier",
    "sklearn_version": sklearn.__version__,
    "python_version": sys.version,
    "features": list(X_train.columns),
    "target": "churn",
    "metrics": {"f1": 0.842, "roc_auc": 0.913},
    "trained_at": datetime.utcnow().isoformat(),
    "data_hash": hashlib.md5(pd.util.hash_pandas_object(X_train).values).hexdigest(),
    "git_commit": subprocess.check_output(["git", "rev-parse", "HEAD"]).decode().strip(),
}

joblib.dump({"model": model, "metadata": metadata}, "model_v1.2.0.joblib")

# Convention: semantic versioning
# v1.0.0 -> initial release
# v1.1.0 -> retrained on new data (backward compatible)
# v2.0.0 -> breaking change (new features, new preprocessing)

ONNX 수출

ONNX가 크로스 플랫폼 모델 형식입니다 — sklearn 파이프라인을 한 번 변환하면 Python 의존성 없이 어디서든(Python, C++, Java, JavaScript, Go) 실행됩니다. 프로덕션에 이상적입니다: 학습 환경(Python)과 서빙 환경(예: Go 마이크로서비스)이 달라도 됩니다. ONNX 런타임이 많은 모델에서 sklearn보다 빠릅니다. 주의: 모든 sklearn transformer와 모델에 ONNX 등가물이 있는 것은 아닙니다 — 확정 전에 skl2onnx 지원을 확인하세요.

machine-learning
# pip install skl2onnx onnxruntime
from skl2onnx import convert_sklearn
from skl2onnx.common.data_types import FloatTensorType
import onnxruntime as rt

# Convert sklearn pipeline to ONNX
initial_type = [("float_input", FloatTensorType([None, X_train.shape[1]]))]
onnx_model = convert_sklearn(full_pipe, initial_types=initial_type,
                              target_opset=15)

with open("model.onnx", "wb") as f:
    f.write(onnx_model.SerializeToString())

# Run inference in any language (Python, C++, Java, JS, Go, ...)
sess = rt.InferenceSession("model.onnx")
input_name = sess.get_inputs()[0].name
predictions = sess.run(None, {input_name: X_test.astype(np.float32)})[0]

# Benefits: no Python at inference, fast, cross-platform

모델 모니터링 기본

세상이 바뀌면서 모델은 프로덕션에서 저하됩니다 — 드리프트를 모니터링하세요. 데이터 드리프트: 입력 특성의 분포 변화(예: 사용자 인구통계 이동). 개념 드리프트: 특성과 타깃의 관계 변화(예: 사기 패턴 진화). PSI(Population Stability Index)가 단순하고 해석 가능한 드리프트 지표입니다 — 0.25를 넘으면 재학습이 필요합니다. 드리프트 경보를 주기적 재학습 스케줄과 결합하세요. 사후 분석을 가능하게 하려 항상 예측을 로그하세요.

machine-learning
# After deployment, monitor for:
# 1. Data drift: input distribution changes
# 2. Concept drift: P(y|X) changes
# 3. Prediction drift: output distribution changes
# 4. Performance degradation: metric drops over time

# Simple data drift check: PSI (Population Stability Index)
def psi(expected, actual, bins=10):
    expected_pct = np.histogram(expected, bins=bins)[0] / len(expected)
    actual_pct   = np.histogram(actual,   bins=bins)[0] / len(actual)
    # Avoid log(0)
    expected_pct = np.clip(expected_pct, 1e-4, None)
    actual_pct   = np.clip(actual_pct,   1e-4, None)
    return np.sum((actual_pct - expected_pct) * np.log(actual_pct / expected_pct))

# PSI < 0.1: stable, 0.1-0.25: minor drift, > 0.25: significant drift
for col in X.columns:
    score = psi(X_train[col], X_new[col])
    if score > 0.25:
        print(f"Drift detected in {col}: PSI={score:.3f}")

재학습 전략

데이터가 바뀌는 속도에 따라 재학습 전략을 고르세요. 스케줄형(가장 단순, 예측 가능). 성능 트리거형(반응적, 필요할 때만 재학습). 드리프트 트리거형(성능 하락 전 조기 경보). 온라인 학습(사기나 추천처럼 빠르게 바뀌는 데이터의 지속 갱신). 새 모델을 최근 데이터에서 현재 모델과 대조 검증하고, 실시간 예측을 비교하려 섀도 배포하고, 지표가 후퇴하면 자동 롤백을 두세요.

machine-learning
# 1. Scheduled retraining (simplest)
#    Retrain weekly/monthly regardless of performance
schedule = "0 2 * * 0"  # every Sunday at 2am

# 2. Performance-triggered retraining
#    Retrain when a metric drops below threshold
if current_f1 < production_f1 * 0.95:  # 5% drop
    trigger_retrain()

# 3. Drift-triggered retraining
#    Retrain when PSI exceeds threshold
if max_psi > 0.25:
    trigger_retrain()

# 4. Online learning (incremental updates)
from sklearn.linear_model import SGDClassifier
model = SGDClassifier()
for X_batch, y_batch in stream:
    model.partial_fit(X_batch, y_batch, classes=[0, 1])

# Always:
# - Validate new model beats old on recent data before promoting
# - Shadow deploy: run new model in parallel, compare predictions
# - Roll back automatically if metrics regress
# - Keep training data fresh (drop old samples)
18

정규화

L1 (Lasso) vs L2 (Ridge)

L1(Lasso)이 절댓값 패널티를 더해 일부 계수를 정확히 0으로 몰아넣습니다 — 내장 특성 선택으로, 많은 특성이 무관할 때 이상적입니다. L2(Ridge)가 제곱 패널티를 더해 계수를 부드럽게 줄입니다 — 많은 특성이 각자 조금씩 기여할 때 더 낫습니다. ElasticNet이 둘을 섞으며 특성이 상관될 때 선호됩니다(단독 Lasso는 하나를 무작위로 고르고 나머지를 0으로 만듭니다). 패널티가 공정해지도록 항상 먼저 특성을 스케일하세요.

machine-learning
from sklearn.linear_model import Lasso, Ridge, ElasticNet
import numpy as np

# L1 (Lasso): penalty = alpha * sum(|coef|)
# Drives some coefficients to exactly 0 -> sparse -> feature selection
lasso = Lasso(alpha=0.1)
lasso.fit(X_train_scaled, y_train)
print("Non-zero coefs:", (lasso.coef_ != 0).sum(), "/", len(lasso.coef_))

# L2 (Ridge): penalty = alpha * sum(coef^2)
# Shrinks coefficients smoothly toward 0, keeps all features
ridge = Ridge(alpha=1.0)
ridge.fit(X_train_scaled, y_train)

# ElasticNet: mix of L1 and L2
# penalty = alpha * (l1_ratio * L1 + (1 - l1_ratio) * L2)
en = ElasticNet(alpha=0.1, l1_ratio=0.5)
en.fit(X_train_scaled, y_train)

# Rule of thumb:
# - L1: many features, only a few matter (sparse)
# - L2: many features, all matter a little
# - ElasticNet: correlated features (Lasso picks one randomly)

트리 정규화

트리에서는 max_depth와 min_samples_leaf가 가장 강한 정규화기입니다 — 트리가 개별 샘플을 암기하지 않게 막습니다. ccp_alpha가 비용-복잡도 가지치기를 합니다(더 원칙적인 사후 가지치기). 랜덤 포레스트에서는 max_features와 bootstrap이 무작위성을 통한 정규화를 더합니다. 그라디언트 부스팅에서는 learning_rate와 early_stopping이 결정적입니다(낮은 LR + 조기 중단 + 충분한 트리가 보통 이깁니다). Subsample과 colsample_bytree가 확률성을 통한 추가 정규화를 더합니다.

machine-learning
from sklearn.ensemble import RandomForestClassifier
from sklearn.tree import DecisionTreeClassifier

# Decision tree regularization hyperparameters
tree = DecisionTreeClassifier(
    max_depth=5,             # limit tree depth (strongest lever)
    min_samples_split=20,    # min samples to split a node
    min_samples_leaf=10,     # min samples per leaf
    max_leaf_nodes=20,       # cap total leaves
    max_features="sqrt",     # features considered per split
    ccp_alpha=0.01,          # cost-complexity pruning
)

# Random forest adds more regularization via:
rf = RandomForestClassifier(
    n_estimators=200,
    max_depth=None,
    min_samples_leaf=5,
    max_features="sqrt",     # random feature subset per split
    bootstrap=True,          # bagging
    max_samples=0.8,         # subsample ratio
)

# For boosting (XGBoost), also use:
# - learning_rate (smaller = more regularization)
# - subsample, colsample_bytree (randomness)
# - reg_lambda, reg_alpha (L2/L1 on leaf weights)
# - gamma (minimum loss reduction to split)
# - early_stopping_rounds

Dropout & BatchNorm (딥러닝)

Dropout이 학습 중 활성화를 무작위 0으로 만들어 네트워크가 중복 표현을 학습하게 강제합니다 — 강한 정규화기입니다. 항상 큰 레이어에서 높게, 작은 레이어에서 낮게, 출력에서는 보통 0입니다. BatchNorm이 배치별로 활성화를 정규화해 학습을 안정화하고 온건한 정규화 효과를 더합니다(배치 통계가 노이즈를 더함). 기억: dropout과 batchnorm은 train과 eval에서 다르게 동작합니다 — 추론에는 항상 model.eval(), 학습 재개에는 model.train()을 호출하세요.

machine-learning
import torch.nn as nn

model = nn.Sequential(
    nn.Linear(784, 256),
    nn.BatchNorm1d(256),     # normalize activations -> faster, stable training
    nn.ReLU(),
    nn.Dropout(0.5),         # randomly zero 50% of activations during training

    nn.Linear(256, 128),
    nn.BatchNorm1d(128),
    nn.ReLU(),
    nn.Dropout(0.3),         # less dropout closer to output

    nn.Linear(128, 10),      # no dropout before output (or use very low)
)

# IMPORTANT: dropout is OFF during inference (model.eval())
# BatchNorm uses batch stats in training and running stats in eval

# Common patterns:
# - Higher dropout in big layers, lower in small layers
# - No dropout right after input or right before output
# - BatchNorm before activation (debated; try both)

조기 중단

조기 중단이 검증 손실이 개선을 멈추면 학습을 중단해 과적합을 막고 연산을 아낍니다. 항상 최선 모델(가장 낮은 val loss)을 저장하세요 — 최종 모델은 과적합했을 수 있습니다. patience가 몇 개의 비개선 에폭을 참을지 제어합니다. 그라디언트 부스팅에서는 early_stopping_rounds가 트리 수준에서 같은 일을 합니다. 조기 중단이 가장 높은 가치, 가장 낮은 노력의 정규화기 중 하나입니다 — 딥러닝에서는 항상 쓰세요.

machine-learning
import torch

best_val_loss = float("inf")
patience, counter = 5, 0
best_state = None

for epoch in range(max_epochs):
    train_loss = train_one_epoch(model, train_loader, optimizer, criterion)
    val_loss   = validate(model, val_loader, criterion)

    if val_loss < best_val_loss:
        best_val_loss = val_loss
        counter = 0
        best_state = {k: v.clone() for k, v in model.state_dict().items()}
    else:
        counter += 1
        if counter >= patience:
            print(f"Early stopping at epoch {epoch}")
            break

# Restore the best model
model.load_state_dict(best_state)

# For XGBoost/LightGBM, use early_stopping_rounds:
# model.fit(X_train, y_train,
#           eval_set=[(X_val, y_val)],
#           early_stopping_rounds=20)

데이터 증강

데이터 증강은 라벨 있는 데이터가 제한적일 때 가장 강한 정규화기입니다 — 라벨을 보존하는 변환으로 데이터셋을 합성 확장합니다. 이미지: 뒤집기, 자르기, 색 지터, 회전(도메인에 맞게 — 의료 X-ray는 뒤집지 말고, 자연 이미지는 뒤집으세요). 텍스트: 동의어 교체, 역번역, 무작위 삭제. 표 형식: SMOTE(불균형)나 mixup(회귀). 증강이 사실상 공짜 라벨 데이터를 줍니다.

machine-learning
# Images (torchvision)
import torchvision.transforms as T

train_transform = T.Compose([
    T.RandomResizedCrop(224),
    T.RandomHorizontalFlip(),
    T.ColorJitter(brightness=0.2, contrast=0.2, saturation=0.2),
    T.RandomRotation(10),
    T.ToTensor(),
    T.Normalize(mean=[0.485, 0.456, 0.406], std=[0.229, 0.224, 0.225]),
])

# Text (NLPAug or simple Python)
import random
def augment_text(text):
    # Synonym replacement, random deletion, back-translation
    words = text.split()
    if random.random() < 0.3:
        idx = random.randrange(len(words))
        words[idx] = synonym(words[idx])
    if random.random() < 0.2:
        words = [w for w in words if random.random() > 0.1]
    return " ".join(words)

# Tabular (SMOTE for imbalance, mixup for regression)
# mixup: X_mix = alpha*X1 + (1-alpha)*X2, y_mix = alpha*y1 + (1-alpha)*y2

Was this helpful?

Learning path

Learn from scratch

Learn this language from the ground up with structured lessons.