AI 개발 공부 공간

AI, 머신러닝, 딥러닝, Python & PyTorch, 실전 프로젝트

머신러닝/머신러닝: 심화 내용

회귀 모델 하이퍼파라미터 튜닝

qordnswnd123 2024. 12. 20. 09:41

1. 하이퍼파라미터

1.1 하이퍼파라미터

하이퍼파라미터는 머신러닝 모델을 학습할 때 설정하는 외부 구성 값들을 의미합니다.

이 값들은 모델 학습 과정 자체에 의해 학습되지 않으며, 모델의 성능에 큰 영향을 미칠 수 있습니다.

하이퍼파라미터에는 학습률, 트리의 깊이, 배치 크기, 에포크 수 등이 있으며 사용할 모델의 종류마다 다릅니다.

 

1.2 하이퍼파라미터 튜닝

하이퍼파라미터 튜닝은 이러한 파라미터들의 최적의 조합을 찾는 과정을 말하여, 이를 통해 모델의 성능을 최대화할 수 있습니다.

 

1.3 하이퍼파라미터 튜닝 코드(Ridge 모델의 알파값)

 

1)Ridge 모델 교차검증

from sklearn.datasets import make_regression
from sklearn.model_selection import train_test_split

# 연습용 데이터 생성
X, y = make_regression(n_samples=100, n_features=2, noise=0.1, random_state=1)

# 훈련 데이터와 테스트 데이터 분리
X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.2, random_state=1)
from sklearn.linear_model import Ridge

ridge_model = Ridge() # 모델 객체 정의
from sklearn.model_selection import cross_val_score

scores = cross_val_score(ridge_model, X_train, y_train, scoring='neg_mean_squared_error')
scores # 교차검증 neg_MSE 점수
array([-2.83839588, -2.27326453, -3.15435097, -2.3522752 , -5.7908437 ])

 

2) alpha 값이 변함에 따라 모델 성능 변화 확인

import numpy as np
from sklearn.model_selection import KFold

# K-Fold 교차 검증 설정
kf = KFold(n_splits=5, shuffle=True, random_state=40)

# alpha 값의 후보 리스트
alpha_list = [0.0001, 0.0002, 0.0003, 0.0004, 0.0005, 0.0006, 0.0007, 0.0008]
scores_list = []

# 각 alpha에 대한 교차 검증 수행
for alpha in alpha_list:
    ridge_model = Ridge(alpha=alpha) # 모델 객체 정의
    scores = cross_val_score(ridge_model, X_train, y_train, scoring='neg_mean_squared_error', cv=kf) # 교차검증
    scores_list.append(np.mean(scores)) # 점수 저장

scores_list
[-0.009961574660232828,
 -0.00996131342479463,
 -0.009961114852547201,
 -0.009960978942643922,
 -0.00996090569423835,
 -0.009960895106483417,
 -0.009960947178533557,
 -0.009961061909540138]
# 최적 alpha 값 및 성능 확인
best_score = max(scores_list) # 최고득점
print(f"Best Score: {best_score}")

optimal_alpha = alpha_list[np.argmax(scores_list)] # 최고득점에서의 alpha값
print(f"Optimal alpha: {optimal_alpha}")
Best Score: -0.009960895106483417
Optimal alpha: 0.0006

 

3) alpha 값이 변함에 따라 모델 성능 변화 시각화

import matplotlib.pyplot as plt

# 결과 시각화
plt.figure(figsize=(10,6))
plt.plot(alpha_list, scores_list, marker='o', linestyle='--')
plt.xlabel('Alpha')
plt.ylabel('Cross-Validation Score (Neg Mean Squared Error)')
plt.title('Alpha vs. CV Score')
plt.xscale('log')
plt.show()