본문 바로가기
AI/ML

[ML] 모델 파인튜닝

by hyeok1235 2024. 8. 14.

가장 적합해보이는 모델 후보들을 여러개 선택했다면, 더 좋은 성능을 위해서 모델을 파인튜닝하는 과정을 거쳐야 한다. 

* 파인튜닝 (Fine-tuning) = 사전에 학습된 모델에 새로운 데이터를 훈련시켜 전이학습을 진행하는 방법

 

1. Grid Search

Grid Search는 어떤 hyperparameter들을 어떤 값들로 조정할지 정하면, cross-validation을 사용해서 모든 경우의 성능을 확인하는 기법이다. 

 

# Grid Search 코드 예시
from sklearn.model_selection import GridSearchCV

full_pipeline = Pipeline([
    ("preprocessing", preprocessing),
    ("random_forest", RandomForestRegressor(random_state=42)),
])
param_grid = [
    {'preprocessing__geo__n_clusters': [5, 8, 10],
     'random_forest__max_features': [4, 6, 8]},
    {'preprocessing__geo__n_clusters': [10, 15],
     'random_forest__max_features': [6, 8, 10]},
]
grid_search = GridSearchCV(full_pipeline, param_grid, cv=3,
                           scoring='neg_root_mean_squared_error')
grid_search.fit(housing, housing_labels)

 

param_grid 안에 있는 2개의 딕셔너리 값 안에서의 조합을 따져보면, 3x3 + 2x3 = 15으로 총 15가지 조합이 나온다. 만약 3-fold cross validation을 사용하면 15*3으로 45번 훈련을 한다. 수동으로 hyperparameter를 조정하는 과정을 생략해준 다는 것에서는 유의미하지만, 연산량이 너무나도 많아진다는 단점이 있다. 

 

2. Randomized Search

Randomized Search는 상대적으로 적은 수의 hyperparameter만을 확인한다. 매 iteration마다 랜덤하게 hyperparameter를 설정하여 성능을 확인한다. grid search보다 연산 시간이 줄어들 뿐만이 아니라, 다음과 같은 3가지 상황에서도 유용하게 사용된다.

1) hyperparameter 값이 이산적 값이 아니라 연속적 값인 경우, grid search는 값을 지정해줘야 하지만 randomized search는 알아서 값들을 선택한다.

2) 특정 hyperparamter가 유의미한 영향을 주지 않을 때, grid search는 이런 hyperparameter에도 시간을 쓰게 되지만 random search에서는 영향을 크게 주지 않는다.

3) 조정해야 하는 hyperparameter가 많은 경우, grid search가 실험해봐야 하는 경우는 기하급수적으로 증가한다. 하지만 randomized search는 실험해보는 경우의 수를 지정할 수 있기 때문에 더 실용적이다. 

# Randomized Search 코드 예시
from sklearn.model_selection import RandomizedSearchCV
from scipy.stats import randint

param_distribs = {'preprocessing__geo__n_clusters': randint(low=3, high=50),
                  'random_forest__max_features': randint(low=2, high=20)}

rnd_search = RandomizedSearchCV(
    full_pipeline, param_distributions=param_distribs, n_iter=10, cv=3,
    scoring='neg_root_mean_squared_error', random_state=42)

rnd_search.fit(housing, housing_labels)

 

3. Ensemble Methods

하나의 decision tree보다 random forest의 성능이 더 좋은 것처럼, 여러 개의 모델을 결합함으로써 모델을 파인튜닝할 수도 있다. 각 모델에서 생기는 error 값과 종류가 다르기 때문에, 결합함으로써 서로를 보완할 수 있다.

 


◆ 모델 분석

어떤 attribute가 예측을 하는데 상대적으로 많은 영향을 미치는지와 얼마나 정확한지를 표시할 수 있다.

>>> final_model = rnd_search.best_estimator_  # includes preprocessing
>>> feature_importances = final_model["random_forest"].feature_importances_
>>> feature_importances.round(2)
array([0.07, 0.05, 0.05, 0.01, 0.01, 0.01, 0.01, 0.19, [...], 0.01])
>>> sorted(zip(feature_importances,
...            final_model["preprocessing"].get_feature_names_out()),
...            reverse=True)
...
[(0.18694559869103852, 'log__median_income'),
 (0.0748194905715524, 'cat__ocean_proximity_INLAND'),
 (0.06926417748515576, 'bedrooms__ratio'),
 (0.05446998753775219, 'rooms_per_house__ratio'),
 (0.05262301809680712, 'people_per_house__ratio'),
 (0.03819415873915732, 'geo__Cluster 0 similarity'),
 [...]
 (0.00015061247730531558, 'cat__ocean_proximity_NEAR BAY'),
 (7.301686597099842e-05, 'cat__ocean_proximity_ISLAND')]
728x90
반응형

'AI > ML' 카테고리의 다른 글

[ML] 경사하강법 (Gradient Descent)  (0) 2024.09.05
[ML] 분류 (Classification)  (0) 2024.08.16
[ML] 데이터셋 준비  (0) 2024.08.13
[ML] 모델의 평가와 검증 (Test, Evaluation)  (0) 2024.07.26
[ML] 머신 러닝의 성능 저하 요인  (1) 2024.07.24