320x100
320x100
이번 시간에는 Bayesian Optimization 실습을 진행 하도록 하겠다.
실습의 순서는 크게 다음과 같다.
- 변경할 하이퍼 파라미터의 범위를 설정한다.
- Bayesian Optimization 에 필요한 함수 생성
- Bayesian Optimization를 이용해 하이퍼 파라미터 튜닝
# X에 학습할 데이터를 , y에 목표 변수를 저장해주세요
X = train.drop(columns=['index','quality'])
y = train['qualit']
# 랜덤포레스트의 하이퍼 파라미터의 범위를 dictionary 형태로 지정해주세요
# Key는 랜덤포레스트의 hyperparameter 이름이고, value는 탐색할 범위이다.
rf_parmeter_bounds={
'max_depth' : (1,3) #나무의 깊이
'n_estimators':(30,100),
}
# 함수를 만들어주겠습니다.
# 함수의 구성은 다음과 같습니다.
# 1. 함수에 들어가는 인자 = 위에서 만든 함수의 key값들
# 2. 함수 속 인자를 통해 받아와 새롭게 하이퍼파라미터 딕셔너리 생성
# 3. 그 딕셔너리를 바탕으로 모델 생성
# 4. train_test_split을 통해 데이터 train-valid 나누기
# 5 .모델 학습
# 6. 모델 성능 측정
# 7. 모델의 점수 반환
def rf_bo(max_depth, n_estimators):
rf_params = {
'max_depth' : int(round(max_depth)),
'n_estimators' : int(round(n_estimators)),
}
rf = RandomForestClassifier(rf_params)
X_train, X_valid, y_train, y_valid = train_test_split(X,y,test_size=0.2,)
rf.fit(X_train,y_train)
score = accuracy_score(y_valid,rf.predict(X_valid))
return score
# 이제 Bayesian Optimization을 사용할 준비가 끝났습니다.
# "BO_rf"라는 변수에 Bayesian Optmization을 저장해보세요
BO_rf = BayesianOptimization(f=rf_bo, pbounds=re_parameter_bounds,random_state=0)
# Bayesian Optimization을 실행해보세요
BO_rf.maximize(init_points = 5, n_iter = 5)
# 하이퍼파라미터의 결과값을 불러와 "max_params"라는 변수에 저장해보세요
max_params = BO_rf.max['params']
max_params['max_depth'] = int(max_params['max_depth'])
max_params['n_estimators'] = int(max_params['n_estimators'])
print(max_params)
# Bayesian Optimization의 결과를 "BO_tuend_rf"라는 변수에 저장해보세요
BO_tuend_rf = RandomForestClassifier(max_params)
320x100
320x100
'빅데이터 관련 자료 > Dacon' 카테고리의 다른 글
XGBoost 튜닝 - 2 (0) | 2021.09.29 |
---|---|
XGBoost 튜닝 (0) | 2021.09.28 |
Bayesian Optimization 복습 (0) | 2021.09.27 |
Voting Classifier 실습 (0) | 2021.09.23 |
Voting Classifier 정의 (0) | 2021.09.22 |