일반적인 GBM은 탐욕적(Greedy) 방식으로 트리를 성장시킨 후 가지치기를 하지만, XGBoost는 max_depth에 도달할 때까지 트리를 성장시킨 후, 손실 감소 기여도가 음수인 분기(즉, 모델 성능에 도움이 안 되는 분기)를 역방향으로 가지치기합니다 (Post-pruning).
gamma (또는 min_split_loss) 파라미터를 사용하여 리프 노드를 추가적으로 분할할 최소 손실 감소 값을 지정하여, 이 값보다 작은 손실 감소를 보이는 분기는 수행하지 않습니다.
XGBoost는 Scikit-Learn과 호환되는 래퍼 클래스(XGBClassifier, XGBRegressor)를 제공하여 기존 Scikit-Learn 워크플로우에 쉽게 통합할 수 있습니다.
import xgboost as xgb
from sklearn.datasets import load_breast_cancer
from sklearn.model_selection import train_test_split, GridSearchCV
from sklearn.metrics import accuracy_score, confusion_matrix, classification_report
# 데이터 로드 (유방암 데이터셋 - 이진 분류)
cancer = load_breast_cancer()
X, y = cancer.data, cancer.target
X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.2, random_state=42, stratify=y)
# XGBClassifier 모델 생성 및 학습 (Scikit-Learn 래퍼)
# 주요 하이퍼파라미터 설정 예시
xgb_clf = xgb.XGBClassifier(
objective='binary:logistic', # 이진 분류
n_estimators=100, # 부스팅 라운드 수 (트리 개수)
learning_rate=0.1, # 학습률
max_depth=3, # 트리의 최대 깊이
subsample=0.8, # 각 트리에 사용할 샘플 비율
colsample_bytree=0.8, # 각 트리에 사용할 특성 비율
gamma=0, # 최소 손실 감소
reg_alpha=0, # L1 규제
reg_lambda=1, # L2 규제
use_label_encoder=False, # LabelEncoder 사용 경고 방지 (XGBoost 1.3.0 이상)
eval_metric='logloss', # 평가 지표 (학습 중 출력)
random_state=42
)
# 조기 종료(Early Stopping) 설정하여 학습
# eval_set: 검증 데이터셋. 조기 종료 및 학습 과정 모니터링에 사용
# early_stopping_rounds: 지정된 라운드 동안 성능 향상이 없으면 학습 중단
eval_set = [(X_test, y_test)] # 테스트셋을 검증셋으로 사용 (실제로는 별도 검증셋 권장)
xgb_clf.fit(X_train, y_train,
early_stopping_rounds=10,
eval_set=eval_set,
verbose=True) # verbose=True로 학습 과정 출력
# 예측
y_pred = xgb_clf.predict(X_test)
y_pred_proba = xgb_clf.predict_proba(X_test)[:, 1]
# 평가
accuracy = accuracy_score(y_test, y_pred)
print(f"\nXGBoost 정확도: {accuracy:.4f}")
print("\nConfusion Matrix:\n", confusion_matrix(y_test, y_pred))
print("\nClassification Report:\n", classification_report(y_test, y_pred))
# 특성 중요도 시각화
# xgb.plot_importance(xgb_clf)
# plt.show()