Cross-Validation
Cross-Validation
Evaluating model performance by splitting the data. K-fold is the most common example.
Cross-Validation
Evaluating model performance by splitting the data. K-fold is the most common example.
Cross-validation is a technique for evaluating a model's generalization performance more reliably on limited data. Unlike simply splitting the data into training/test sets once, it performs multiple splits and evaluations to measure the mean and variance of performance. This prevents chance results caused by a particular data split and allows model performance to be estimated more accurately.
The most widely used method is K-Fold cross-validation. The entire dataset is divided into K folds of equal size, and in each iteration, 1 fold is used for validation and the remaining K-1 folds are used for training. Training and evaluation are repeated K times to obtain K performance scores, and their average is used as the final performance. In general, K=5 or K=10 is commonly used.
Variants of cross-validation include Stratified K-Fold, Leave-One-Out (LOO), and Time Series Split. Stratified K-Fold maintains the same class proportions in each fold for classification problems. LOO is an extreme approach that sets K equal to the number of data points, so that only a single sample is used for validation. Time Series Split prevents data leakage, where future data is used to learn about the past, in time series data.
Cross-validation is also used for Hyperparameter tuning. GridSearchCV and RandomizedSearchCV perform cross-validation on multiple Hyperparameter combinations to find the optimal combination. However, because cross-validation requires training the model K times, computational cost increases. If the dataset is large enough, a simple holdout (train/valid/test split) is also a valid alternative.
Examples of various cross-validation techniques and Hyperparameter tuning in Scikit-learn.
# pip install scikit-learn
from sklearn.datasets import load_iris
from sklearn.model_selection import (
cross_val_score, KFold, StratifiedKFold,
GridSearchCV, cross_validate
)
from sklearn.ensemble import RandomForestClassifier
from sklearn.svm import SVC
import numpy as np
# 데이터 로드
X, y = load_iris(return_X_y=True)
# 1. 기본 K-Fold 교차 검증
model = RandomForestClassifier(n_estimators=100, random_state=42)
scores = cross_val_score(model, X, y, cv=5, scoring='accuracy')
print("=== K-Fold 교차 검증 (K=5) ===")
print(f"각 폴드 점수: {scores}")
print(f"평균 정확도: {scores.mean():.4f} (+/- {scores.std() * 2:.4f})")
# 2. Stratified K-Fold (분류 문제에 권장)
skf = StratifiedKFold(n_splits=5, shuffle=True, random_state=42)
scores_stratified = cross_val_score(model, X, y, cv=skf, scoring='accuracy')
print("\n=== Stratified K-Fold 교차 검증 ===")
print(f"평균 정확도: {scores_stratified.mean():.4f} (+/- {scores_stratified.std() * 2:.4f})")
# 3. 다중 메트릭 평가
scoring = ['accuracy', 'precision_macro', 'recall_macro', 'f1_macro']
results = cross_validate(model, X, y, cv=5, scoring=scoring, return_train_score=True)
print("\n=== 다중 메트릭 교차 검증 ===")
for metric in scoring:
test_key = f'test_{metric}'
print(f"{metric}: {results[test_key].mean():.4f} (+/- {results[test_key].std() * 2:.4f})")
# 4. GridSearchCV로 하이퍼파라미터 튜닝
param_grid = {
'C': [0.1, 1, 10],
'kernel': ['rbf', 'linear'],
'gamma': ['scale', 'auto']
}
svc = SVC(random_state=42)
grid_search = GridSearchCV(svc, param_grid, cv=5, scoring='accuracy', n_jobs=-1)
grid_search.fit(X, y)
print("\n=== GridSearchCV 결과 ===")
print(f"최적 하이퍼파라미터: {grid_search.best_params_}")
print(f"최고 교차 검증 점수: {grid_search.best_score_:.4f}")
# 5. 각 폴드별 상세 결과
print("\n=== 폴드별 상세 결과 ===")
cv_results = grid_search.cv_results_
best_idx = grid_search.best_index_
for i in range(5):
print(f"Fold {i+1}: {cv_results[f'split{i}_test_score'][best_idx]:.4f}")
# 결과 예시:
# === K-Fold 교차 검증 (K=5) ===
# 각 폴드 점수: [0.967 0.967 0.933 0.967 1.0]
# 평균 정확도: 0.9667 (+/- 0.0422)