개발하고 싶어요
랜덤포레스트_분류 본문
랜덤포레스트¶
랜덤포레스트의 개요 및 실습¶
랜덤포레스트는 여러 개의 결정 트리 분류기가 전체 데이터에서 배깅 방식(분류기는 동일, 데이터를 랜덤 샘플)으로 각자의 데이터를 샘플링해 개별적으로 학습을 수행한 후 뒤 최종적으로 모든 분류기가 보팅(서로 다른 분류기 결합)을 통해 예측 결정
부트스트래핑 분할 방식 : 여러 개의 데이터 세트를 중첩되게 분리하는 것
In [25]:
# 앞의 사용자 행동 인식 데이터 세트를 randomforestclassifier을 이용해 예측하기
from sklearn.ensemble import RandomForestClassifier
from sklearn.metrics import accuracy_score
import pandas as pd
import 사용자_행동_인식_데이터 as func # 앞 파일의 함수를 사용하기 위하여
import warnings
warnings.filterwarnings('ignore')
# 앞 파일 결정 트리에서 사용한 get_human_dataset()를 이용해 학습/테스트용 dataframe 반환
X_train, X_test, y_train, y_test = func.get_human_dataset()
In [26]:
# 랜덤 포레스트 학습 및 별도의 테스트 세트로 예측 성능 평가
rf = RandomForestClassifier(random_state = 0, max_depth = 8) # 모델 생성
rf.fit(X_train, y_train) # 학습
pred = rf.predict(X_test) # 예측
accuracy = accuracy_score(y_test, pred) # 평가
print('랜덤 포레스트 정확도 : {:.4f}'.format(accuracy))
Out[26]:
RandomForestClassifier(max_depth=8, random_state=0)
In a Jupyter environment, please rerun this cell to show the HTML representation or trust the notebook. On GitHub, the HTML representation is unable to render, please try loading this page with nbviewer.org.
RandomForestClassifier(max_depth=8, random_state=0)
랜덤 포레스트 정확도 : 0.9196
랜덤 포레스트 하이퍼 파라미터 및 튜닝¶
In [28]:
# gridsearchCV를 이용해 랜덤 포레스트의 하이퍼 파라미터를 튜닝
from sklearn.model_selection import GridSearchCV
params = {
'max_depth' : [8, 16, 24],
'min_samples_leaf' : [1, 6, 12],
'min_samples_split' : [2, 8, 16]
}
# randomforestclassifier객체 생성 후 gridsearchCV 수행
rf = RandomForestClassifier(n_estimators = 100, random_state = 0, n_jobs = -1)
grid = GridSearchCV(rf, param_grid = params, cv = 2, n_jobs = -1)
grid.fit(X_train, y_train)
print('최적 하이퍼 파라미터 : \n', grid.best_params_)
print('최고 예측 정확도 : {:.4f}'.format(grid.best_score_))
Out[28]:
GridSearchCV(cv=2, estimator=RandomForestClassifier(n_jobs=-1, random_state=0),
n_jobs=-1,
param_grid={'max_depth': [8, 16, 24],
'min_samples_leaf': [1, 6, 12],
'min_samples_split': [2, 8, 16]})
In a Jupyter environment, please rerun this cell to show the HTML representation or trust the notebook. On GitHub, the HTML representation is unable to render, please try loading this page with nbviewer.org.
GridSearchCV(cv=2, estimator=RandomForestClassifier(n_jobs=-1, random_state=0),
n_jobs=-1,
param_grid={'max_depth': [8, 16, 24],
'min_samples_leaf': [1, 6, 12],
'min_samples_split': [2, 8, 16]})
RandomForestClassifier(n_jobs=-1, random_state=0)
RandomForestClassifier(n_jobs=-1, random_state=0)
최적 하이퍼 파라미터 :
{'max_depth': 16, 'min_samples_leaf': 6, 'min_samples_split': 2}
최고 예측 정확도 : 0.9165
In [29]:
# 추출된 최적 하이퍼 파라미터로 다시 학습 후 별도의 테스트 데이터 세트에서 예측 성능 측정
rf = RandomForestClassifier(n_estimators = 100, min_samples_leaf = 6, max_depth = 16, min_samples_split = 2, random_state = 0) # 모델 생성
rf.fit(X_train, y_train) # 학습
pred = rf.predict(X_test) # 예측
print('예측 정확도 : {:.4f}'.format(accuracy_score(y_test, pred))) # 평가
Out[29]:
RandomForestClassifier(max_depth=16, min_samples_leaf=6, random_state=0)
In a Jupyter environment, please rerun this cell to show the HTML representation or trust the notebook. On GitHub, the HTML representation is unable to render, please try loading this page with nbviewer.org.
RandomForestClassifier(max_depth=16, min_samples_leaf=6, random_state=0)
예측 정확도 : 0.9260
In [35]:
# feature_importances_속성을 이용해 알고리즘이 선택한 피처의 중요도 확인
import matplotlib.pyplot as plt
import seaborn as sns
ftr_importances_values = rf.feature_importances_ # 피처 중요도 값
ftr_importances = pd.Series(ftr_importances_values, index = X_train.columns)
ftr_importances[:5]
ftr_top20 = ftr_importances.sort_values(ascending = False)[:20] # 상위 20개만 추출
plt.figure(figsize = (8, 6));
plt.title('Feature importances Top 20');
sns.barplot(x = ftr_top20, y = ftr_top20.index);
'ML' 카테고리의 다른 글
베이지안 최적화 기반 (0) | 2024.01.23 |
---|---|
lightgbm_분류 (0) | 2024.01.23 |
xgboost_분류 (0) | 2024.01.23 |
붓꽃 품종 예측하기 (0) | 2024.01.22 |
평가 (1) | 2024.01.22 |