DEVELOPMENT/AI

머신러닝(ML) - RandomForest 모델

hongjw 2020. 12. 29. 17:11

RandomForest란?

앙상블 머신러닝(ensemble machine learning) 모델로 여러개의 결정트리(decision tree)가 모여서 만들어진 것이다. 

 

원리

수많은 feature를 기반으로 하나의 결정트리를 만든다면 트리의 가지가 많아질 것이고, 이는 오버피팅이 발생할 확률이 높다. 하지만 랜덤포레스트는 여러개의 feature 중 랜덤으로 몇가지의 feature를 선택해서 여러개의 결정트리를 만들 수 있다. 이렇게 만들어진 여러 결정트리들이 내린 예측 값들 중 가장 많이 나온 값을 최종 예측값으로 결정하게 된다. 

즉, 하나의 결정트리를 만드는 것이 아니라 여러 개의 작은 결정트리를 만드는 것이다. 여러 개의 작은 결정트리가 예측한 값들 중 가장 많은 값(분류일 경우) 혹은 평균값(회귀일 경우)을 최종 예측 값으로 정하는 것입니다.

 

RandomForest 구현

import numpy as np
import matplotlib.pyplot as plt
import pickle

from sklearn import datasets
from sklearn.model_selection import train_test_split
from sklearn.metrics import recall_score
from sklearn.metrics import precision_score
from sklearn.metrics import f1_score
from sklearn.metrics import confusion_matrix
from sklearn.ensemble import RandomForestClassifier
from keras import models


# data preprocessing
print("[*] Start : RandomForest Classification")

datasets = np.loadtxt('파일.csv', delimiter=',',skiprows=1)
xy_data = datasets   # exclude header
train_set, test_set = train_test_split(xy_data, test_size=0.3, random_state=123)   
print('Training Length : ', len(train_set), 'Test Length : ', len(test_set))

x_train_data = train_set[:,1:]
y_train_data = train_set[:,:1].reshape(-1,)

x_test_data = test_set[:,1:]
y_test_data = test_set[:,:1].reshape(-1,)

print("[x_train_data]",x_train_data.shape)
print("[y_train_data]", y_train_data.shape)
print("[x_test_data]", x_test_data.shape)
print("[y_test_data]", y_test_data.shape)

rf = RandomForestClassifier(n_estimators=60, random_state=123)
rf.fit(x_train_data, y_train_data)

print("train_accuracy :",rf.score(x_train_data, y_train_data))
print("\n")

print("test_accuracy :",rf.score(x_test_data, y_test_data))
print("\n")
y_pred = rf.predict(x_test_data)
print(y_pred)

print(confusion_matrix(y_test_data, y_pred))

#confusion matrix (1:악성, 0:정상)
# TP : 1을 1이라고 하는 경우 
# FN : 1을 0이라고 하는 경우 
# FP : 0을 1이라고 하는 경우 
# TN : 0을 0이라고 하는 경우 

- n_estimators : 랜덤포레스트 안의 결정트리 갯수

- max_features : 무작위로 선택할 feature의 갯수 (max_features 값이 크면 랜덤포레스트의 트리들이 매우 비슷해지고, 값이 작으면 랜덤포레스트의 트리들이 서로 매우 달라질 것이다. 일반적으로 max_features는 default 값을 쓴다.)

 

모델 저장

import joblib

joblib.dump(rf, "모델.pkl")

 

 

 

참고

>> bkshin.tistory.com/entry/%EB%A8%B8%EC%8B%A0%EB%9F%AC%EB%8B%9D-5-%EB%9E%9C%EB%8D%A4-%ED%8F%AC%EB%A0%88%EC%8A%A4%ED%8A%B8Random-Forest%EC%99%80-%EC%95%99%EC%83%81%EB%B8%94Ensemble

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

train, test, validation 데이터셋  (0) 2020.12.30
딥러닝(DL) - CNN 모델  (0) 2020.12.30
딥러닝(DL) - DNN 모델  (0) 2020.12.30