Python 튜토리얼

기초

  • moneyIcon Prize : 교육
  • 9,999명 D-100719

 

Lv4 튜닝 5/6 python 파이썬 모델 튜닝 / Voting Classifier(1)

2021.09.03 15:24 2,780 Views

안녕하세요.👩‍🔧👨‍🔧 이번시간에는 Random Forest, XGBoost, Light GBM 총 3개의 모델을 튜닝 하고 Voting Classifier로 만들어 보도록 하겠습니다.

순서는 다음 과 같습니다.


  1. 개별 모델을  basian optimization로 튜닝
  2. 튜닝 된 모델을 Voting Classifier로 생성
  3. Voting Classifier 학습 및 test 데이터 예측
  4. 최종 정답 파일 제출.

실습 내용이 많아 이번 시간에는 Voting Classifier 정의 까지 실습하고 다음 시간에 이어서 실습 하도록 하겠습니다.

그럼 바로 실습을 진행해보도록 하겠습니다. 🕵️‍♂️


Random Forest 튜닝

-------------------------------------------------------------------------------------------------------------------------------------------------------------

# X에 학습할 데이터를, y에 목표 변수를 저장해주세요

X = train.drop(columns = ['index', 'quality'])

y = train['quality']


# 랜덤포레스트의 하이퍼 파라미터의 범위를 dictionary 형태로 지정해주세요

## Key는 랜덤포레스트의 hyperparameter이름이고, value는 탐색할 범위 입니다.

rf_parameter_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_depthn_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 = rf_parameter_bounds,random_state = 0)


# Bayesian Optimization을 실행해보세요

BO_rf.maximize(init_points = 5, n_iter = 5)


-------------------------------------------------------------------------------------------------------------------------------------------------------------


XGBoost 튜닝

-------------------------------------------------------------------------------------------------------------------------------------------------------------

# X에 학습할 데이터를, y에 목표 변수를 저장해주세요

X = train.drop(columns = ['index''quality'])

y = train['quality']


# XGBoost의 하이퍼 파라미터의 범위를 dictionary 형태로 지정해주세요

## Key는 XGBoost hyperparameter이름이고, value는 탐색할 범위 입니다.

xgb_parameter_bounds = {

                      'gamma' : (0,10),

                      'max_depth' : (1,3), # 나무의 깊이

                      'subsample' : (0.5,1)

                      }


# 함수를 만들어주겠습니다.

# 함수의 구성은 다음과 같습니다.

# 1. 함수에 들어가는 인자 = 위에서 만든 함수의 key값들

# 2. 함수 속 인자를 통해 받아와 새롭게 하이퍼파라미터 딕셔너리 생성

# 3. 그 딕셔너리를 바탕으로 모델 생성

# 4. train_test_split을 통해 데이터 train-valid 나누기

# 5 .모델 학습

# 6. 모델 성능 측정

# 7. 모델의 점수 반환


def xgb_bo(gamma,max_depthsubsample):

  xgb_params = {

              'gamma' : int(round(gamma)),

              'max_depth' : int(round(max_depth)),

               'subsample' : int(round(subsample)),      

              }

  xgb = XGBClassifier(**xgb_params)


  X_train, X_valid, y_train, y_valid = train_test_split(X,y,test_size = 0.2, )


  xgb.fit(X_train,y_train)

  score = accuracy_score(y_valid, xgb.predict(X_valid))

  return score


# 이제 Bayesian Optimization을 사용할 준비가 끝났습니다.

# "BO_xgb"라는 변수에 Bayesian Optmization을 저장해보세요

BO_xgb = BayesianOptimization(f = xgb_bo, pbounds = xgb_parameter_bounds,random_state = 0)


# Bayesian Optimization을 실행해보세요

BO_xgb.maximize(init_points = 5, n_iter = 5)

-------------------------------------------------------------------------------------------------------------------------------------------------------------


Light GBM

-------------------------------------------------------------------------------------------------------------------------------------------------------------

# X에 학습할 데이터를, y에 목표 변수를 저장해주세요

X = train.drop(columns = ['index''quality'])

y = train['quality']


# LGBM의 하이퍼 파라미터의 범위를 dictionary 형태로 지정해주세요

## Key는 LGBM hyperparameter이름이고, value는 탐색할 범위 입니다.

lgbm_parameter_bounds = {

                      'n_estimators' : (30,100),

                      'max_depth' : (1,3), # 나무의 깊이

                      'subsample' : (0.5,1)

                      }


# 함수를 만들어주겠습니다.

# 함수의 구성은 다음과 같습니다.

# 1. 함수에 들어가는 인자 = 위에서 만든 함수의 key값들

# 2. 함수 속 인자를 통해 받아와 새롭게 하이퍼파라미터 딕셔너리 생성

# 3. 그 딕셔너리를 바탕으로 모델 생성

# 4. train_test_split을 통해 데이터 train-valid 나누기

# 5 .모델 학습

# 6. 모델 성능 측정

# 7. 모델의 점수 반환


def lgbm_bo(n_estimators,max_depthsubsample):

  lgbm_params = {

              'n_estimators' : int(round(n_estimators)),

              'max_depth' : int(round(max_depth)),

               'subsample' : int(round(subsample)),      

              }

  lgbm = LGBMClassifier(**lgbm_params)


  X_train, X_valid, y_train, y_valid = train_test_split(X,y,test_size = 0.2, )


  lgbm.fit(X_train,y_train)

  score = accuracy_score(y_valid, lgbm.predict(X_valid))

  return score


# 이제 Bayesian Optimization을 사용할 준비가 끝났습니다.

# "BO_lgbm"라는 변수에 Bayesian Optmization을 저장해보세요

BO_lgbm = BayesianOptimization(f = lgbm_bo, pbounds = lgbm_parameter_bounds,random_state = 0)


# Bayesian Optimization을 실행해보세요

BO_lgbm.maximize(init_points = 5, n_iter = 5)

-------------------------------------------------------------------------------------------------------------------------------------------------------------


Voting Classifier 생성

-------------------------------------------------------------------------------------------------------------------------------------------------------------

# 모델 정의 (튜닝된 파라미터로)

LGBM = LGBMClassifier(max_depth = 2.09,n_estimators=60, subsample = 0.8229)

XGB = XGBClassifier(gamma =  4.376, max_depth = 2.784, subsample = 0.9818)

RF = RandomForestClassifier(max_depth = 3.0, n_estimators = 35.31)


# VotingClassifier 정의

VC = VotingClassifier(estimators=[('rf',RF),('xgb',XGB),('lgbm',LGBM)],voting = 'soft')

-------------------------------------------------------------------------------------------------------------------------------------------------------------


[Colab 실습 링크]


↩️ 오늘의 파이썬 리스트

#데이콘_101 #AI #머신러닝 #딥러닝 #파이썬 #파이선  #데이터분석 #데이터사이언티스트 #코랩 #Python  #colab #kaggle #pandas #numpy #sckit-learn # read_csv #Bayesian #Optimization #bayesianoptimization #베이지안옵최적화



로그인이 필요합니다
0 / 1000
그린티
2021.09.13 21:39

done

다욤
2021.09.20 02:27

done

왼쪽눈썹왁싱
2021.11.02 15:35

changhyeon
2022.01.03 17:50

done

dbnoid
2022.01.19 10:06

hijihyo
2022.01.29 19:17

Kdata
2022.05.04 14:58

krooner
2022.05.20 00:11

dirno
2022.08.02 15:51

highllight
2023.02.12 22:40

이전 글
인덱싱을 위한 Pandas .iloc .loc 사용 방법 데이터 분석 및 조작을위한
Competition - Python 튜토리얼
Likes 4
Views 1,710
Comments 0
일 년 전
현재 글
Lv4 튜닝 5/6 python 파이썬 모델 튜닝 / Voting Classifier(1)
Competition - Python 튜토리얼
Likes 7
Views 2,780
Comments 10
3년 전
다음 글
다음 글이 존재하지 않습니다.