Gradient Boosting

**특징

  • 여러개의 결정트리를 묶어 강력한 모델을 만듦
  • RF와 달리 이전 트리의 오차를 보완하는 방식으로 순차적으로 트리 생성 -> 무작위성이 없음
  • 강력한 사전가지치기 사용
  • 보통 5가지 이하의 얕은 트리를 사용 -> 적은 메모리
  • 얕은 트리(weak learner로 통칭)를 많이 연결, 각 트리는 데이터의 일부에 대해서만 예측을 수행 -> 트리를 많이 추가할 수록 성능이 좋아짐

**주요 매개변수

  • 사전가지치기, 트리의 개수 외에
  • learning rate: 이전 트리의 오차를 얼마나 강하게 보장할 것인지를 제어 -> 학습률이 크면 보정을 강하게 하므로 모델의 복잡도 증가

 

 

 

- iris 데이터를 이용한 Gradient Boosting 작업 순서 

# 필요한 라이브러리 추가
from sklearn.ensemble import GradientBoostingClassifier
from sklearn.model_selection import train_test_split
from sklearn import datasets


# 1 데이터 로딩
iris = datasets.load_iris()

# 2 데이터 분할
X = iris.data
y = iris.target

X_train, X_test, y_train, y_test= train_test_split(X,y,test_size=0.3,random_state = 10)

# 3 모델 객체 생성
gtb = GradientBoostingClassifier()  # default 값 max_depth = 3

# 4 fitting model
gtb.fit(X_train, y_train)

# 5 훈련 데이터 
print("훈련 세트 점수 : {:.3f}".format(gtb.score(X_train,y_train)))
print( "테스트 세트 점수 : {:.3f}".format(gtb.score(X_test,y_test)))

 

 

위와 같이 default로 사용할 경우 이미지와 같은 GradientBoostingClassifier가 만들어집니다. 

훈련 세트 점수 : 1.000 테스트 세트 점수 : 0.978 

 

 

적합한 max_depth를 찾고 n_en_estimators 를 찾는 과정을 예제를 통해 학습해보겠습니다.

breast_cancer 데이터 이용해 분석하기

 

# 1. 데이터 불러오기
from sklearn.datasets import load_breast_cancer
breast = load_breast_cancer()


# 2. 데이터 분류
Xb = breast.data
yb = breast.target
Xb_train, Xb_test, yb_train, yb_test = train_test_split(Xb, yb, test_size=0.3, random_state = 43)


# 3. modelling

## 3.1 max_depth = 1
gtb1 = GradientBoostingClassifier(max_depth=1).fit(Xb_train, yb_train)
print("훈련 세트 점수 : {:.3f}".format(gtb1.score(Xb_train,yb_train)))
print( "테스트 세트 점수 : {:.3f}".format(gtb1.score(Xb_test,yb_test)))
# 결과 : 훈련 세트 점수 : 0.990  테스트 세트 점수 : 0.977


## 3.2 max_depth = 2
gtb2 = GradientBoostingClassifier(max_depth=2).fit(Xb_train, yb_train)
print("훈련 세트 점수 : {:.3f}".format(gtb2.score(Xb_train,yb_train)))
print( "테스트 세트 점수 : {:.3f}".format(gtb2.score(Xb_test,yb_test)))
# 결과 : 훈련 세트 점수 : 1.000 테스트 세트 점수 : 0.977


## 3.3 max_depth = 3
gtb3 = GradientBoostingClassifier(max_depth=3).fit(Xb_train, yb_train)
print("훈련 세트 점수 : {:.3f}".format(gtb3.score(Xb_train,yb_train)))
print( "테스트 세트 점수 : {:.3f}".format(gtb3.score(Xb_test,yb_test)))
# 결과 : 훈련 세트 점수 : 1.000 테스트 세트 점수 : 0.977

# 위의 결과를 봤을 때, max_depth = 2일 때 적합하다고 예상할 수 있습니다.


# 4. 모델링 반복(max_depth = 2를 이용하여)
train_acc, test_acc = [],[]
n_estimators = range(5,201,5)

for n_estimator in n_estimators:
    # 모델 생성
    gtb3_depth_n = GradientBoostingClassifier(n_estimators=n_estimator, random_state=n_estimator, max_depth=2)
    
    gtb3_depth_n.fit(Xb_train, yb_train)
    
    train_acc.append(gtb3_depth_n.score(Xb_train, yb_train))
    test_acc.append(gtb3_depth_n.score(Xb_test, yb_test))
    
# 5. estimator 변화에 따른 결과 그래프로 확인
import matplotlib.pyplot as plt

plt.figure(figsize = (20,10))
plt.plot(n_estimators, train_acc, label="train",marker='o')
plt.plot(n_estimators, test_acc, label="test",marker='o')
plt.ylabel('accuracy')
plt.xlabel('number of n_estimators')
plt.legend(fontsize=15)


# 6. 최종 모델 확인
gtb3_depth_n = GradientBoostingClassifier(n_estimators=155, random_state=155, max_depth=2, learning_rate=0.1)
gtb3_depth_n.fit(Xb_train, yb_train)
    
# 훈련 정확도 출력
print("훈련 세트 점수 : {:.3f}".format(gtb3_depth_n.score(Xb_train,yb_train)))
print( "테스트 세트 점수 : {:.3f}".format(gtb3_depth_n.score(Xb_test,yb_test)))

# learning_rate를 높이면 보정을 강하게 하기 때문에 복잡한 모델을 만듭니다.(default = 0.1)
# n_estimator 값을 키우면 ensemble에 트리가 더 많이 추가되어 모델의 복잡도가 커지고 train 세트를 더 정확하게 fitting합니다.

훈련 세트 점수 : 1.000 테스트 세트 점수 : 0.982

위의 그래프를 확인하면 n_esimators가 155일 때가 가장 높은 test 점수를 가지기 때문에 155로 모델에 적용시킨 후 최종 결과를 뽑아냈습니다.

 

간단하게 gradient boosting 에 대해 공부해보았습니다.

궁금한 사항, 부족한 사항은 댓글에 담겨주세요!

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

[Python] LinearRegression(수치예측) - Ridge  (0) 2019.08.28
[Python] LinearRegression(수치예측)  (0) 2019.08.28
[Python] RandomForest 예제  (0) 2019.08.27
[Python] RandomForest  (0) 2019.08.27
[Python] DecisionTree  (0) 2019.08.27

+ Recent posts