시작하기
머신러닝이란?
머신러닝은 손으로 쓴 규칙을 따르는 대신 데이터에서 일반화하는 시스템을 만듭니다. 세 가지 패러다임(지도, 비지도, 강화)이 대부분의 실제 문제를 커버합니다. 구조화된 워크플로우 — 특히 깨끗한 테스트 셋을 따로 두는 것 — 을 따르면 평가에 과적합하는 치명적 죄를 막습니다.
# 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(프로덕션 친화적) 중 고르세요 — 둘 다 같은 영역을 커버합니다.
# 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를 쓰세요.
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을 주며, 불균형 문제에서 정확도 하나보다 훨씬 정보적입니다.
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도 필요합니다 — '맞아야' 하는데 안 맞는 결과를 디버깅할 때 유용합니다.
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"데이터 전처리
결측값 처리
전체 데이터셋에 imputer를 fit하면 테스트 통계가 학습에 새어 나갑니다 — 항상 train에만 fit하세요. Median이 mean보다 이상치에 강합니다. 범주형 특성에는 'most_frequent'나 'constant'를 쓰세요. KNN 대체는 다변량 구조를 잡을 수 있지만 큰 데이터에선 비쌉니다. 결측 자체가 정보일 수 있으니('is_missing' 지시자 추가) 판단하세요.
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 절대 금지.
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'가 테스트 시 보지 못한 범주의 오류를 막습니다. 고카디널리티 범주형(예: 우편번호)은 차원 폭발을 피하려 타깃/카운트 인코딩이 더 낫습니다.
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로 평가하세요 — 불균형 데이터에 정확도만 쓰는 것은 금물입니다.
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), 유지할지는 도메인에 따라 결정하세요 — 때로 이상치가 바로 관심 사례입니다(사기, 이상 감지).
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]특성 공학
다항 & 상호작용 특성
PolynomialFeatures가 x^2, x*y 등을 새 특성으로 더해 선형 모델이 비선형 관계를 잡게 합니다. interaction_only가 순수 제곱을 피하며, 교차항만 원할 때 유용합니다. 특성 수가 조합적으로 폭발하므로 — 과적합 방지를 위해 항상 정규화(Ridge/Lasso)와 짝지으거나 차원 축소 뒤에 쓰세요.
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 인코딩하세요.
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를 설정하세요.
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가 시계열용 간단한 추세 특성입니다.
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에 적용하세요.
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)지도 학습
선형 & 로지스틱 회귀
선형 모델은 빠르고 해석 가능하며 강한 기준선입니다. LogisticRegression은 기본 L2 정규화를 씁니다; 낮은 C가 더 강한 정규화입니다. 다중 클래스에는 softmax를 씁니다. 계수가 특성 중요도를 보여주지만 스케일링 후에만 그렇습니다 — 스케일링되지 않은 특성은 계수 비교를 불가하게 만듭니다. 복잡한 모델 전에 항상 선형 기준선으로 시작하세요.
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를 시도하세요.
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을 쓰세요.
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나 트리 앙상블을 쓰세요.
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)을 쓰세요.
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}")비지도 학습
K-Means 클러스터링
K-Means가 클러스터 내 분산을 최소화해 데이터를 k개 구형 클러스터로 나눕니다. n_init=10이 알고리즘을 10개 무작위 초기화로 실행하고 최선을 유지합니다(sklearn 1.4에서 기본값이 바뀜). k는 팔꿈치(inertia)나 실루엣 점수로 고르세요(실루엣이 더 원칙적). K-Means는 구형·동일 크기 클러스터를 가정하므로 — 비구형 클러스터에는 DBSCAN이나 Gaussian Mixture를 쓰세요.
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를 쓰세 요.
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을 쓰세요.
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은 새 샘플도 생성할 수 있습니다 — 데이터 증강에 유용합니다.
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이 기대 이상 비율을 정합니다; 도메인 지식에 따라 조율하세요.
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)회귀
선형 회귀 & 정규화 변형
OLS가 정규화 없이 제곱 오류를 최소화합니다 — 다중공선성 데이터에서 분산이 높습니다. Ridge(L2)가 계수를 부드럽게 줄여 많은 특성이 관여할 때 좋습니다. Lasso(L1)가 일부 계수를 0으로 몰아 특성 선택을 수행합니다. ElasticNet이 둘을 섞어 특성이 상관될 때 유용합니다. 패널티가 특성 전반에 공정해지도록 정규화 회귀 전에 항상 특성을 스케일하세요.
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.
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')가 평균 대신 백분위를 예측합니다 — 하/상 분위수 모델을 결합해 예측 구간을 만들면, 불확실성 추정이 필요할 때 유용합니다.
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 범위를 고르는 훌륭한 진단 도구입니다.
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를 로그 변환) 시사합니다. 잔차의 정규성은 추론(신뢰 구간)에는 중요하지만 예측 정확도에는 그렇지 않습니다.
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분류
이진 분류 기본
predict가 하드 클래스 라벨을 반환하고(임계값 0.5), predict_proba가 확률을 반환합니다 — 보통 더 유용합니다. 기본 0.5 임계값은 거의 최적이 아닙니다: 더 높은 재현율(더 많은 양성 포착, 예: 암 검진)에는 낮추고, 더 높은 정밀도(거짓 경보 감소, 예: 스팸 필터)에는 올리세요. ROC-AUC가 확률이 양성을 음성보다 얼마나 잘 순위 매기는지 임계값과 무관하게 측정합니다.
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를 쓰세요.
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에서는 오른쪽 위를 노리세요.
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가 예측 확률의 품질을 측정합니다(낮을수록 좋음).
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해 이를 고칩니다. 보정은 확률에 따라 행동할 때(위험 점수화, 임계값 조율) 중요합니다 — 하드 클래스 예측만 쓴다면 필요 없습니다.
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()클러스터링 심화
k 고르기: 팔꿈치 & 실루엣
팔꿈치 방법이 inertia가 빠르게 떨어지지 않기 시작하는 k를 찾습니다 — 주관적이고 때로 보이지 않습니다. 실루엣 점수가 더 원칙적입니다: 각 점이 자기 클러스터와 가장 가까운 타 클러스터와 얼마나 유사한지 측정합니다(범위 -1~1). 실루엣 > 0.5는 합리적 구조, > 0.7은 강력합니다. 항상 둘 다 시각화하고 팔꿈치가 불명확하면 실루엣을 선호하세요.
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 값들을 시각적으로 비교하세요.
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보다 더 의미 있는 클러스터를 내는 경우가 많습니다.
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 둘 다 우연을 보정하고 순열 불변입니다. 최고의 단일 지표는 없습니다 — 여러 개를 쓰고 클러스터를 시각화하세요.
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 시각화하세요.
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()차원 축소
PCA (주성분 분석)
PCA가 가장 많은 분산을 잡는 직교 축(주성분)을 찾아 대부분의 정보를 보존하며 고차원 데이터를 압축하게 합니다. 스케일링이 중요합니다 — PCA가 특성 스케일에 민감합니다. 95% 분산을 자동 유지하려 n_components=0.95를 쓰세요. PCA는 선형이고 빠르며 분산 = 정보를 가정하는데 — 항상 참은 아닙니다(저분산 특성이 판별적인 경우가 있습니다).
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까지).
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차원으로 압축하세요.
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를 쓰세요.
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 separabilityTruncated SVD (희소 데이터용)
TruncatedSVD(텍스트에서는 LSA라고도 함)가 희소 데이터용 PCA 대안입니다 — 데이터를 중심화하지 않아 TF-IDF 같은 희소 행렬에서 동작합니다. TF-IDF와 결합하면 '토픽' — 함께 나타나는 단어들의 그룹 — 을 만듭니다. 더 나은 토픽 모델링에는 NMF나 현대 임베딩 기반 접근을 시도하세요. 텍스트에는 약 100-300개 컴포넌트를 유지하세요; 올바른 수는 코퍼스 크기와 하류 작업에 달렸습니다.
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)모델 평가
교차 검증
교차 검증이 여러 train/test 분할에 걸쳐 평균해 견고한 성능 추정을 줍니다. StratifiedKFold가 분류에서 클래스 균형을 유지합니다(불균형 데이터에 필수). RepeatedStratifiedKFold가 다른 분할로 CV를 여러 번 실행합니다 — 더 높은 연산 비용으로 더 안정적인 추정. 모델 선택에는 단일 train/test 분할이 아니라 항상 CV를 쓰세요.
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 분산의 최고 진단 도구입니다. 높은 학습 점수와 낮은 검증 점수 사이의 큰 간격은 과적합입니다(데이터 추가, 정규화, 단순화). 둘 다 낮고 가까우면 과소적합입니다(더 복잡한 모델이나 특성 추가). 곡선이 오른쪽 끝에서도 개선 중이면 더 많은 데이터가 도움이 됩니다.
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검증 곡선 (하이퍼파라미터)
검증 곡선이 성능을 단일 하이퍼파라미터 값에 대해 그립니다 — 모델 동작 이해와 그리드 검색 전 합리적 범위 찾기에 유용합니다. 학습 점수는 모델 복잡도와 함께 계속 오르지만 검증 점수는 정점에 찍힌 뒤 떨어집니다. 정점이 스위트 스팟이고, 그 전이 과소적합, 뒤가 과적합입니다.
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조차 다수 클래스만 예측하는 모델을 가릴 수 있습니다.
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가 최악의 사례를 보여줍니다. 커스텀 비대칭 손실(예: 과소 예측에 더 큰 패널티)이 실제 비용에 맞습니다: 품절 비용과 재고 과잉 비용은 다릅니다.
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()교차 검증 전략
K-Fold 변형
올바른 CV 전략 선택이 결정적입니다. KFold가 기본입니다. 분류에는 StratifiedKFold(클래스 균형 유지). 샘플이 상관되어 있으면(사용자/환자당 여러 행) GroupKFold — train과 val 사이 정보 누출을 막습니다. 시간 데이터에는 TimeSeriesSplit(항상 과거로 학습, 미래로 검증). 잘못된 CV 전략은 낙관적인 추정을 줍니다.
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를 쓰면 극도로 낙관적인 추정이 나옵니다 — 초보자의 흔한 실수입니다.
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의 가장 흔한 무소식 버그 중 하나입니다.
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 루프가 전체 튜닝 절차를 진짜 분리된 폴드에서 평가합니다. 결과는 완전한 모델링 파이프라인(튜닝 포함)이 새 데이터에서 어떻게 동작할지의 편향 없는 추정입니다. 정직한 벤치마킹, 특히 모델 비교에 쓰세요.
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하지 마세요.
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)하이퍼파라미터 튜닝
그리드 검색
GridSearchCV가 모든 조합을 철저히 평가합니다 — thorough하지만 비쌉니다(조합 폭발). 작고 잘 고른 매개변수 그리드가 있을 때 쓰세요. 항상 적절한 scoring 지표를 전달하세요(기본은 accuracy로, 불균형 분류에서는 틀립니다). refit=True가 최선 모델을 전체 학습 데이터로 재학습해 반환된 추정기가 바로 쓸 수 있게 합니다.