하이퍼파라미터 튜닝
하이퍼파라미터 튜닝(Hyperparameter Tuning)은 모델의 외부 설정을 최적화하여 일반화 성능을 극대화하는 과정입니다.학습 목표
- GridSearchCV와 RandomizedSearchCV를 사용할 수 있습니다.
- Optuna를 활용한 베이지안 최적화를 적용할 수 있습니다.
- 탐색 공간을 효율적으로 설계할 수 있습니다.
튜닝 실습
from sklearn.model_selection import GridSearchCV
from sklearn.ensemble import RandomForestClassifier
from sklearn.datasets import load_iris
X, y = load_iris(return_X_y=True)
param_grid = {
"n_estimators": [50, 100, 200],
"max_depth": [3, 5, 10, None],
"min_samples_split": [2, 5, 10]
}
grid = GridSearchCV(
RandomForestClassifier(random_state=42),
param_grid,
cv=5,
scoring="accuracy",
n_jobs=-1,
verbose=1
)
grid.fit(X, y)
print(f"최적 파라미터: {grid.best_params_}")
print(f"최적 점수: {grid.best_score_:.4f}")
from sklearn.model_selection import RandomizedSearchCV
from scipy.stats import randint, uniform
param_distributions = {
"n_estimators": randint(50, 500),
"max_depth": [3, 5, 10, 20, None],
"min_samples_split": randint(2, 20),
"min_samples_leaf": randint(1, 10),
"max_features": uniform(0.1, 0.9)
}
random_search = RandomizedSearchCV(
RandomForestClassifier(random_state=42),
param_distributions,
n_iter=50, # 50개 조합만 시도
cv=5,
scoring="accuracy",
n_jobs=-1,
random_state=42
)
random_search.fit(X, y)
print(f"최적 파라미터: {random_search.best_params_}")
print(f"최적 점수: {random_search.best_score_:.4f}")
import optuna
from sklearn.model_selection import cross_val_score
def objective(trial):
"""Optuna 목적 함수: 교차검증 점수 최대화"""
params = {
"n_estimators": trial.suggest_int("n_estimators", 50, 500),
"max_depth": trial.suggest_int("max_depth", 3, 20),
"min_samples_split": trial.suggest_int("min_samples_split", 2, 20),
"min_samples_leaf": trial.suggest_int("min_samples_leaf", 1, 10),
"max_features": trial.suggest_float("max_features", 0.1, 1.0),
}
model = RandomForestClassifier(**params, random_state=42)
scores = cross_val_score(model, X, y, cv=5, scoring="accuracy")
return scores.mean()
# 최적화 실행
study = optuna.create_study(direction="maximize")
study.optimize(objective, n_trials=100, show_progress_bar=True)
print(f"최적 파라미터: {study.best_params}")
print(f"최적 점수: {study.best_value:.4f}")
# 최적화 과정 시각화
optuna.visualization.plot_optimization_history(study)
optuna.visualization.plot_param_importances(study)
방법 비교
| 방법 | 탐색 전략 | 효율성 | 적합한 상황 |
|---|---|---|---|
| GridSearchCV | 전수 조사 | 낮음 | 파라미터 2-3개, 값 범위 좁을 때 |
| RandomizedSearchCV | 무작위 샘플링 | 중간 | 파라미터 많거나 범위 넓을 때 |
| Optuna | 베이지안 (TPE) | 높음 | 대규모 탐색, 효율 중시 |
Q: 어떤 하이퍼파라미터를 먼저 튜닝해야 하나요?
Q: 어떤 하이퍼파라미터를 먼저 튜닝해야 하나요?
일반적으로 모델 성능에 가장 큰 영향을 미치는 파라미터를 먼저 튜닝합니다. 랜덤 포레스트는 n_estimators, max_depth 순으로, XGBoost는 learning_rate, n_estimators, max_depth 순으로 중요합니다.
Q: 튜닝 결과가 교차검증보다 테스트에서 나쁘면 어떻게 하나요?
Q: 튜닝 결과가 교차검증보다 테스트에서 나쁘면 어떻게 하나요?
하이퍼파라미터 튜닝 자체가 과적합될 수 있습니다. Nested CV를 사용하면 이 문제를 방지할 수 있습니다.
체크리스트
- GridSearchCV와 RandomizedSearchCV를 사용할 수 있다
- Optuna로 베이지안 최적화를 수행할 수 있다
- 탐색 공간을 효율적으로 설계할 수 있다
- 튜닝 결과를 올바르게 해석할 수 있다

