본문 바로가기
프로그래밍/기타 Python 모듈

[XGBoost] XGBoost 모형 학습하기 (feat. XGBClassifier, XGBRegressor)

by 부자 꽁냥이 2022. 11. 5.

XGBoost 모듈에는 XGBoost 모형을 학습할 수 있는 다양하고 강력한 기능을 제공한다. 이번 포스팅에서는 XGBoost를 이용한 XGBoost 모형을 학습하고 결과를 확인하는 방법을 알아보려고 한다. XGBoost는 분류 문제, 회귀 문제에 대하여 모두 적용할 수 있으므로 각각의 경우에 대하여 알아보자.

 

- 목차 -

1. 분류 문제(XGBoostClassifier)

2. 회귀 문제(XGBRegressor)

 

XGBoost에 대한 개념은 아래에 포스팅해두었으니 궁금한 분들은 참고하면 좋다.

 

21. XGBoost에 대해서 알아보자

 

21. XGBoost에 대해서 알아보자

이번 포스팅에서는 부스팅 계열에 떠오르는 샛별 XGBoost에 대해서 알아보려고 한다. 여기에서는 XGBoost의 개념, 알고리즘 동작 원리를 예제와 함께 알아보고자 한다. - 목차 - 1. XGBoost란 무엇인가?

zephyrus1111.tistory.com


   1. 분류 문제(XGBClassifier)

XGBoost 모형을 분류 문제에 적용하기 위하여 분류 데이터는 붓꽃 데이터(Iris Dataset)를 사용한다. XGBoost 모듈에서는 XGBClassifier 클래스를 이용하여 분류 모형을 학습할 수 있다. 이때 기본 학습기(base learner)의 개수 n_estimators, 개별 나무의 최대 깊이 max_depth 그리고 튜닝 파라미터 gamma 등을 설정한다. 또한 변수 중요도 타입 importance_type도 설정할 수 있다. 나머지 인자는 주석을 참고하며 자세한 내용은 XGBoost 문서를 참고하기 바란다.

 

모형 학습은 fit 메서드의 설계 행렬(Design Matix) X와 반응 변수 y를 입력하고 호출하면 된다.

 

import pandas as pd
import warnings
warnings.filterwarnings('ignore')
 
from sklearn.datasets import load_iris, load_boston
from xgboost.sklearn import XGBClassifier, XGBRegressor
 
iris = load_iris()
df = pd.DataFrame(iris.data, columns=iris.feature_names)
df['species'] = iris.target
 
X = df.drop('species', axis=1)
y = df['species']
 
clf = XGBClassifier(
            n_estimators=50, ## 붓스트랩 샘플 개수 또는 base_estimator 개수
            max_depth=5, ## 개별 나무의 최대 깊이
            gamma = 0, ## gamma
            importance_type='gain', ## gain, weight, cover, total_gain, total_cover
            reg_lambda = 1, ## tuning parameter of l2 penalty
            random_state=100
        ).fit(X,y)

 

모형을 학습한 뒤 예측과 성능 평가를 다음과 같이 할 수 있다.

 

## 예측
print(clf.predict(X)[:3]) 
print()
## 성능 평가
print('정확도 : ', clf.score(X,y)) ## 테스트 성능 평가 점수(Accuracy)
print()
## 변수 중요도
for i, feature in enumerate(iris.feature_names):
    print(f'{feature} : {clf.feature_importances_[i]}')

 


   2. 회귀 문제(XGBRegressor)

이번에는 XGBoost 모형을 회귀 문제에 적용해보자. 데이터는 보스턴 집값 데이터를 선택했다. XGBoost 모듈에서는 XGBRegressor 클래스를 이용하여 회귀 모형을 학습할 수 있다. 이때 XGBClassifier와 마찬가지로 기본 학습기(base learner)의 개수 n_estimators, 개별 나무의 최대 깊이 max_depth 그리고 튜닝 파라미터 gamma 등을 설정한다. 분류 모형과 마찬가지로 변수 중요도 타입 importance_type도 지정할 수 있다. 나머지 인자는 주석을 참고하며 자세한 내용은 XGBoost 문서를 참고하기 바란다.

 

boston = load_boston()
df = pd.DataFrame(boston.data, columns=boston.feature_names)
df['MEDV'] = boston.target
 
X = df.drop('MEDV', axis=1)
y = df['MEDV']
 
reg = XGBRegressor(
            n_estimators=50, ## 붓스트랩 샘플 개수 또는 base_estimator 개수
            max_depth=5, ## 개별 나무의 최대 깊이
            gamma = 0, ## gamma
            importance_type='gain', ## gain, weight, cover, total_gain, total_cover
            reg_lambda = 1, ## tuning parameter of l2 penalty
            random_state=100
        ).fit(X,y)

 

회귀 모형 학습 후 예측과 성능 평가를 다음과 같이 할 수 있다.

 

## 예측
print(reg.predict(X)[:3]) 
print()
## 성능 평가
print('R2 : ', reg.score(X,y)) ## 테스트 성능 평가 점수(Accuracy)
print()
## 변수 중요도
for i, feature in enumerate(boston.feature_names):
    print(f'{feature} : {reg.feature_importances_[i]}')

 


댓글


맨 위로