Decision Tree - Boosting

2022. 1. 2. 19:06머신러닝

반응형

Boosting은 용어에서 느껴지듯이 점점 강력한(예측력, 정확도가 높은) 모델을 만들어가는 알고리즘입니다. Weak learner에서 Strong learner로 발전하게 되는데, parallel하게 모형을 학습하여 조합하는 bagging과 다르게 sequential하게 만들어진 모델들을 조합하는 방식입니다.

Boosting 모델 중에서 gradient boosting model - 2tree을 예시로 Boosting concept를 정리해보겠습니다.

1) 실제값에 적합, $y=f_1(x)$

2) 첫번째 모형의 오차에 적합, $y-f_1(x) = f_2(x)$  

3) 최종 예측값 결정, $\widehat{y} = f_1(x) + f_2(x)$

위에서 확인하는 것처럼, 첫번째 모형의 결과가 두번째 모형에도 지속적으로 영향을 미치게 됩니다. 이를 sequential하게 학습한다고 표현하며, 이렇게 sequentail하게 학습한 모형들의 조합을 통해 결과를 산출하는 것을 Boosting이라고 합니다.

Boosting 모델 중 가장 유명한 Adaboost와 Gradeint boosting model을 정리해보도록 하겠습니다.

[1] Adaboost

Adaboost는 Weak learner들의 결과값을 결합하여 Strong learner을 만듭니다. 특히 순차적으로 학습이 이루어질 때 기존의 learner들이 잘 학습하지 못하는(정확한 결과를 제공해주지 못하는) 관측값들에 대해 가중치를 주어 학습을 하여, 기존 learner들의 약점을 보완해주게 됩니다.

이때 관측값에 가중치를 준다는 의미는, Weak learner을 만들 때 Sampling을 수행하게 되는데 Sampling을 할 때 가중치가 높은 관측값이 더 많이 추출되게 한다는 것입니다.

Adaboost의 알고리즘을 요약하면 아래와 같습니다.

1) 모든 관측값에 동일한 가중치를 부여합니다.(Sampling시 모두 동일한 확률로 추출됩니다.)

2) 데이터의 Subset을 활용하여 Weak 모델을 학습합니다.

3) 해당 모델을 이용하여 전체 데이터에 대해서 Prediction을 수행합니다.

4) 실제값과 비교하여 Error를 측정하고, 정확하게 분류하지 못한 관측값에 더 높은 가중치를 부여합니다.

5) 가중치에 기반하여 관측값을 Sampling 하고 2)~4)를 반복합니다.(error가 변하지 않을 때 or 정한 esimator 수에 도달했을 때 등)

Python을 활용하여 Adaboost를 적용해보겠습니다.

from sklearn.datasets import load_iris
from sklearn.model_selection import train_test_split
from sklearn.ensemble import AdaBoostClassifier
from sklearn.metrics import accuracy_score
import pandas as np
import numpy as np


iris= load_iris()

iris_df = pd.DataFrame(data=iris.data, columns=iris.feature_names)
iris_df['label']=iris.target

train_x, valid_x, train_y, valid_y = train_test_split(iris_df.loc[:,iris_df.columns[0:3]], iris_df['label'], test_size=0.33, random_state=7)


abc = AdaBoostClassifier(n_estimators=50, learning_rate=1, random_state=0)
model = abc.fit(train_x, train_y)
pred_y = model.predict(valid_x)


print("accuracy:{}".format(accuracy_score(valid_y, pred_y))) ## 'accuracy:0.9'

[2] Gradient Boosting

Gradient Boosting은 처음에 언급한것과 같이 앞선 모델의 Residual에 적합하는 Tree model들을 만드는 것입니다.

1) 첫 번째 예측값 결정 , $y=f_1(x)$

2) 첫번째 모형의 오차에 적합, $y-f_1(x) = f_2(x)$  

3) 두 번째 모형의 오차에 적합, $y- f_1(x)-f_2(x) = f_3(x)$

4) Tree model 수만큼 진행

위와 같이 정해신 Tree model 수만큼 Residual들을 적합해가면서 정확도를 향상시킵니다. 각 모델에 결과값에 가중치를 줄 수 있으며, 최종 적합값은 아래와 같습니다.

Python을 활용하여 Gradient Boosting을 적합해보겠습니다.

from sklearn.ensemble import GradientBoostingClassifier

grad_boost_clf = GradientBoostingClassifier(n_estimators=100, max_depth = 3, learning_rate = 0.1, random_state = 7)
model = grad_boost_clf.fit(train_x, train_y)
pred_y = model.predict(valid_x)


print("accuracy:{}".format(accuracy_score(valid_y, pred_y))) ## 'accuracy:0.88'
반응형

'머신러닝' 카테고리의 다른 글

Decision Tree - Bagging  (0) 2021.10.19
Decision Tree Model  (0) 2021.10.15
Tree-Based Model  (0) 2021.10.06
Generalized Additive Models(GAM)  (0) 2021.08.15
모델 평가 및 선정 > Bootstrap Method  (0) 2021.06.28