-
랜덤 포레스트 & 랜덤 서치머신러닝(+딥러닝) 2023. 8. 10. 19:52
문제
랜덤 포레스트에 사용되는 최적의 하이퍼 파라미터를 랜덤 서치를 통해 찾아보고, 이 파라미터를 이용해 훈련해 보자
코드
랜덤 서치는
- 파라미터를 랜덤으로 조합해 모델을 생성
- 교차 검증으로 score 를 산출
- 최고 score 의 파라미터를 찾음
랜덤 포레스트는 결정 트리 (Decision Tree) 기반으로 앙상블 학습을 함
기본 세팅
Decision Tree 에서는 sklearn.preprocessing.StandardScaler 로 데이터를 표준화할 필요가 없다.
import numpy as np import pandas as pd from sklearn.model_selection import train_test_split wine = pd.read_csv('https://bit.ly/wine_csv_data') data = wine[['alcohol', 'sugar', 'pH']].to_numpy() target = wine['class'].to_numpy() train_input, test_input, train_target, test_target = train_test_split( data, target, test_size=0.2, random_state=42 )
랜덤하게 모델을 만들고 교차 검증으로 평가해 최적의 파라미터 찾기
from sklearn.ensemble import RandomForestClassifier from scipy.stats import uniform, randint params = { 'min_impurity_decrease': uniform(0.0001, 0.001), 'max_depth': randint(20, 50), 'min_samples_split': randint(2, 25), 'min_samples_leaf': randint(1, 25) } from sklearn.model_selection import RandomizedSearchCV gs = RandomizedSearchCV(RandomForestClassifier(random_state=42), params, n_iter=100, n_jobs=-1, random_state=42) gs.fit(train_input, train_target)
n_iter=100 횟수 만큼 랜덤 파라미터로 훈련을 해 본다. (n_iter 만큼 모델 생성해 봄)
gs.fit(...) 을 하면 찾아낸 최적의 파라미터로 훈련을 한다.
생성한 모델 살펴보기
# 찾아낸 최적의 파라미터 보기 gs.best_params_ # {'max_depth': 36, # 'min_impurity_decrease': 0.00013734818874921442, # 'min_samples_leaf': 6, # 'min_samples_split': 16} # 이름은 mean_test_score 이지만 교차 검증에 사용된 검증 세트에 대한 스코어이다. np.max(gs.cv_results_['mean_test_score']) # 0.8751201228992374 # 만들어진 최적의 모델로 테스트 세트에 대해 평가 rf = gs.best_estimator_ rf.score(test_input, test_target) # 0.8676923076923077
'머신러닝(+딥러닝)' 카테고리의 다른 글
확률적 경사 하강법 (+ 로지스틱 회귀) (0) 2023.08.08 릿지 회귀 (0) 2023.08.08 sklearn 으로 학습한 모델을 파일로 저장하기 (0) 2023.08.08