하이퍼파라미터튜닝
만드는 모델의 최고성능을 내기 위해서 하는것, 학습과정을 직접 컨트롤할 수 있는것.
>> 랜덤서치는 더 쉽게 더 넓은 범위를 찾는다. 그러니 먼저 하는것이 좋음.
- GridSearchCV: 검증하고 싶은 하이퍼파라미터들의 수치를 정해주고 그 조합을 모두 검증.
- RandomizedSearchCV: 검증하려는 하이퍼파라미터들의 값 범위를 지정해주면 무작위로 값을 지정해 그 조합을 모두 검증.
Randomized Search CV
1) 하이퍼파라미터를 직접 지정
1. 라이브러리 불러오기
from sklearn.model_selection import RandomizedSearchCV
2. pipe라인을 이용하여 모델 학습(예시는 릿지회귀)
from sklearn.pipeline import make_pipeline
from category_encoders import OneHotEncoder
from sklearn.impute import SimpleImputer
from sklearn.model_selection import cross_val_score
from sklearn.preprocessing import StandardScaler
pipe = make_pipeline(
OneHotEncoder(use_cat_names=True)
, SimpleImputer()
, StandardScaler()
, SelectKBest(f_regression)
, Ridge())
3. 튜닝하고 싶은 하이퍼파라미터 지정 및 범위 지정
# 튜닝할 하이퍼파라미터의 범위를 지정
dists = {
'simpleimputer__strategy': ['mean', 'median'],
'selectkbest__k': range(1, len(X_train.columns)+1),
'ridge__alpha': [0.1, 1, 10]}
4. randomized Search CV 진행
clf = RandomizedSearchCV(
pipe, #파이프라인으로 학습된 모델
param_distributions=dists, #하이퍼파라미터 튜닝 값으로 진행한다
n_iter=50, # 반복 횟수
cv=3, # 교차검증 횟수 (==> n_iter * cv 의 숫자만큼 진행됨)
scoring='neg_mean_absolute_error', # MAE
verbose=1, # 훈련 중지여부를 화면에 출력 (1= progress bar/2= one line per epoch)
n_jobs=-1)
5. randomized Search CV로 train data 학습 진행
clf.fit(X_train, y_train);
Fitting 3 folds for each of 50 candidates, totalling 150 fits
6. 적용시킨 최적의 하이퍼파라미터 확인하기
print('최적 하이퍼파라미터: ', clf.best_params_)
print('MAE: ', -clf.best_score_)
최적 하이퍼파라미터: {'simpleimputer__strategy': 'median', 'selectkbest__k': 55, 'ridge__alpha': 10}
MAE: 18414.633797820472
7. (no 필수) 각 하이퍼파라미터로 만들어진 모델 순위 확인
# rank_test_score: 테스트 순위
# mean_score_time: 예측에 걸리는 시간
pd.DataFrame(clf.cv_results_).sort_values(by='rank_test_score').T
2) scipy.stats 사용해 파라미터 선택을 위한 다양한 분포모듈을 활용
1. 라이브러리 불러오기
from sklearn.model_selection import RandomizedSearchCV
from scipy.stats import randint, uniform
- scipy.stats randint 는 하한 또는 상한 테일 확률의 이름을 명시 적으로 지정할 수있을뿐만 아니라 임의 정수를 도출 할 분포를 지정. 주어진 밀도 함수에서 임의의 간격을 그리기에 유용함.
- scipy.stats uniform 은 지정된 간격 사이에 정해진 인수를 통해 균일한 연속 변수를 생성함.
2. pipeline 이용하여 모델 선택
pipe = make_pipeline(
TargetEncoder(),
SimpleImputer(),
RandomForestRegressor(random_state=2))
3. 최적의 하이퍼파라미터 조건 입력
dists = {
'targetencoder__smoothing': [2.,20.,50.,60.,100.,500.,1000.],# int로 넣으면 error(bug)
'targetencoder__min_samples_leaf': randint(1, 10), # randint 로 범위를 지정
'simpleimputer__strategy': ['mean', 'median'],
'randomforestregressor__n_estimators': randint(50, 500),
'randomforestregressor__max_depth': [5, 10, 15, 20, None],
'randomforestregressor__max_features': uniform(0, 1) # max_features ## uniform은 균등분포
}
4. 위의 모델pipe와 하이퍼 파라미터 조건을 넣어 randomized Search CV진행
clf = RandomizedSearchCV(
pipe,
param_distributions=dists,
n_iter=50,
cv=3,
scoring='neg_mean_absolute_error',
verbose=1,
n_jobs=-1 )
5. train data에 적용하여 학습 진행
clf.fit(X_train, y_train);
Fitting 3 folds for each of 50 candidates, totalling 150 fits
6. 적용한 최적의 하이퍼 파라미터와 평가 지표 출력
print('최적 하이퍼파라미터: ', clf.best_params_)
print('MAE: ', -clf.best_score_)
최적 하이퍼파라미터: {'randomforestregressor__max_depth': 20, 'randomforestregressor__max_features': 0.22612308958451122, 'randomforestregressor__n_estimators': 498, 'simpleimputer__strategy': 'mean', 'targetencoder__min_samples_leaf': 8, 'targetencoder__smoothing': 1000.0}
MAE: 15741.360087309344
7. 만들어진 모델에서 최적의 하이퍼파라미터를 적용시킨 모델을 불러오기
pipe = clf.best_estimator_
bestestimator 는 CV가 끝난 후 찾은 best parameter를 사용해 모든 학습데이터(all the training data)를 가지고 다시 학습(refit)한 상태.
8. 최적의 하이퍼파라미터를 적용시킨 모델로 예측 진행
y_pred = pipe.predict(X_test)
9. 평가지표 확인하기
from sklearn.metrics import mean_absolute_error
mae = mean_absolute_error(y_test, y_pred)
print(f'테스트세트 MAE: ${mae:,.0f}')
테스트세트 MAE: $15,778
GridSearchCV
설정한 모든 가능한 파라미터 조합을 다 시험해보는 방법. 도메인 지식이 어느정도있어 최적 파라미터가 대략적으로 위치하는 범위를 알때 사용하기 좋음.
1. 라이브러리 불러오기
from scipy.stats import randint, uniform
from sklearn.feature_selection import SelectKBest
from sklearn.model_selection import GridSearchCV
2. pipeline을 이용하여 모델 지정
pipe = make_pipeline(
TargetEncoder(),
SimpleImputer(),
PolynomialFeatures(),
SelectKBest(),
RandomForestClassifier()
)
3. 딕셔너리로 parameter 범위 지정
parameters = {'max_depth':[1,2,3], 'min_samples_split':[2,3]}
4. param_grid의 하이퍼 파라미터를 3개의 train, valid set fold로 나누어 테스트 진행
grid_dt = GridSearchCV(pipe, param_grid=parameters, cv=3, refit=True)
5. train data 모델 학습 및 적용
grid_dt.fit(X_train, y_train)
GridSearchCV 객체의 fit( )을 수행하면 최고 성능일 때의 하이퍼 파라미터값과 그때의 평가 결과 값이 각각 best_params_, best_score_ 속성에 기록된다.
6. 최적의 하이퍼파라미터를 찾는 성능 보기
pd.DataFrame(grid_dt.cv_results_).sort_values(by='rank_test_score').T
7. 최적의 파라미터와 정확도 확인
print('GridSearchCV 최적 파라미터:', grid_dt.best_params_)
print('GridSearchCV 최고 정확도:{0:.4f}', .format(grid_dt.best_score_))
GridSearchCV 최적 파라미터: {'max_depth': 3, 'min_samples_split': 2}
GridSearchCV 최고 정확도: 0.9750
8. 최적의 하이퍼파라미터로 학습 진행및 예측
refit=True 상태이므로 최적 성능을 보여주는 파라미터로 학습된 estimator는 best_estimator_로 저장되어 있다. 저장된 best estimator로 처음에 나눴던 테스트 데이터셋에 대해 테스트를 진행한다.
best = grid_dt.best_estimator_
pred = best.predict(X_test)
9. 평가지표 확인: 정확도 측정
from sklearn.metrics import accuracy_score
print('정확도:{:.4f}'.format(accuracy_score(y_test, pred)))
선형회귀, 랜덤포레스트 모델들의 튜닝 추천 하이퍼파라미터
Random Forest
- class_weight (불균형(imbalanced) 클래스인 경우)
- max_depth (너무 깊어지면 과적합)
- n_estimators (적을경우 과소적합, 높을경우 긴 학습시간)
- min_samples_leaf (과적합일경우 높임)
- max_features (줄일 수록 다양한 트리생성)
Logistic Regression
- C (Inverse of regularization strength)
- class_weight (불균형 클래스인 경우)
- penalty
Ridge / Lasso Regression
- alpha