AICE - 지도학습 5

이강민·2023년 8월 18일
0

AICE

목록 보기
16/18
post-thumbnail

그래디언트 부스팅

그래디언트 부스팅은 부스팅 계열의 알고리즘으로 트리 기반의 모델을 직렬로 연결하여 앞선 모델이 예측한 것 중 틀린 데이터에 가중치를 부여하여 더 잘 학습되도록 하는 알고리즘이다.
다른 트리 기반 모델과 마찬가지로 특성의 스케일을 조정하지 않아도 되고 이진 분류나 연속적인 수치 예측에서도 잘 작동한다는 장점이 있다. 하지만 트리기반 모델 특성상 희소한 고차원 데이터에서는 잘 작동하지 않는다.

Mnist(Modified National Institute of Standard And Technology)란?
딥러닝을 공부할 때 가장 많이 나오는 데이터세트 중 하나이다. 데이터의 구조는 숫자 0 ~ 9까지 손글씨 이미지의 집합이며 학습 데이터는 6만개, 테스트 데이터 1만 개로 구성되어 있다. 이때 각각 이미지는 28 x 28 크기이다. 이과정에서 이미지 데이터도 reshape로 변형하여 머신러닝을 적용할 수 있다.

그래디언트 부스팅 실습

데이터준비하기

#tensorflow에서 데이터 불러오기
from tensorflow.keras.datasets.mnist import load_data
#그래프 라이브러리
import matplotlib.pyplot as plt

#데이터 불러오기
(x_train, y_train),(x_test, y_test) = load_data()

#학습 시간고려 2000건 데이터 만 사용
x_train = x_train[:2000]
x_test = x_test[:2000]
y_train = y_train[:2000]
y_test = y_test[:2000]

#샘플 데이터 확인하기
plt.imshow(x_train[2], cmap='Greys')
plt.show()
#샘플데이터 확인
plt.imshow(x_train[3], cmap='Greys')
plt.show()

#학습을 위한 2차원 행렬로 변경
x_train = x_train.reshape(-1,784)
x_test = x_test.reshape(-1,784)
 


알고리즘 별 학습 및 결과 비교

#의사결정나무, 랜덤 포레스트, 그래디언트 부스팅 라이브러리 불러오기
from sklearn.tree import DecisionTreeClassifier
from sklearn.ensemble import RandomForestClassifier
from sklearn.ensemble import GradientBoostingClassifier

#의사결정나무 불러오기 및 학습
dct = DecisionTreeClassifier(random_state=0)
dct.fit(x_train, y_train)
#의사결정나무 학습 결과 저장하기
acc_train_dct = dct.score(x_train, y_train)
acc_test_dct = dct.score(x_test, y_test)

#랜덤 포레스트 불러오기 및 학습
rfc = RandomForestClassifier(random_state=0)
rfc.fit(x_train, y_train)
#랜덤 포레스트 학습 결과 저장
acc_train_rfc = rfc.score(x_train, y_train)
acc_test_rfc = rfc.score(x_test, y_test)

#그래디언트 부스팅 불러오기 및 학습
gbc = GradientBoostingClassifier(random_state = 0, verbose=1)
gbc.fit(x_train, y_train)
#그래디언트 부스팅 학습 결과 저장
acc_train_gbc = gbc.score(x_train, y_train)
acc_test_gbc = gbc.score(x_test, y_test)

#각 알고리즘별 성능 비교
print(f'''의사결정나무 : train_acc = {round(acc_train_dct, 3)}, test_acc={round(acc_test_dct,3)}''')
print(f'''랜덤 포레스트 : train_acc = {round(acc_train_rfc, 3)}, test_acc={round(acc_test_rfc,3)}''')
print(f'''그래디언트 부스팅 : train_acc = {round(acc_train_gbc, 3)}, test_acc={round(acc_test_gbc,3)}''')

#비교 그래프 그리기
import matplotlib.pyplot as plt
acc_list_x = ['dct_train','dct_test','rfc_train','rfc_test','gbc_train','gbc_test']
acc_list_y =[acc_train_dct, acc_test_dct, acc_train_rfc,acc_test_rfc, acc_train_gbc,acc_test_gbc]
colors = ['orange','orange','blue','blue','red','red']
plt.figure(figsize=(4,4))
plt.bar(acc_list_x, acc_list_y, color=colors)
plt.ylim([0.8,1.0])
plt.show()


문제

그래디언트 부스팅 알고리즘 n_estimators를 200으로 설정하여 학습시켜 보고 기존 그래디언트 부스팅 결과와 비교하는 그래프 코드?

from sklearn.ensemble import GradientBoostingClassifier
#기존 그레디언트 부스팅 학습 및 결과 저장
gbc = GradientBoostingClassifier(random_state=0 , verbose=1)
gbc.fit(x_train, y_train)
acc_train_gbc = gbc.score(x_train,y_train)
acc_test_gbc = gbc.score(x_test,y_test)
# n_estimators 200으로 설정한 그레디언트 부스팅 학습 및 결과 저장
gbc_200 = GradientBoostingClassifier(random_state=0, n_estimators=200,verbose=1)
gbc_200.fit(x_train, y_train)
acc_train_gbc_200 = gbc_200.score(x_train, y_train)
acc_test_gbc_200 = gbc_200.score(x_test, y_test)
acc_list_x = ['gbc_train','gbc_test','tune_gbc_train','tune_gbc_test']
acc_list_y = [acc_train_gbc, acc_test_gbc,acc_train_gbc_200,acc_test_gbc_200]
colors = ['orange','orange','blue','blue']

#그래프로 비교하기
import matplotlib.pyplot as plt
plt.figure(figsize=(4,4))
plt.bar(acc_list_x, acc_list_y,color=colors)
plt.ylim([0.8, 1.0])
plt.show()

profile
배움은 끝없이

2개의 댓글

comment-user-thumbnail
2023년 8월 18일

좋은 글 감사합니다.

1개의 답글