πŸ€– AI/ML

XGBoost

Extreme Gradient Boosting

An optimized gradient boosting library. A frequent Kaggle winner.

πŸ“– Detailed Explanation

XGBoost (eXtreme Gradient Boosting) is an optimized distributed gradient boosting library developed by Tianqi Chen. Since its release in 2014, it has won numerous Kaggle competitions with performance that surpasses deep learning in tabular data analysis. It uses decision trees (Decision Tree) as its base learner, and creates a strong learner by sequentially training multiple weak learners using boosting, a method of ensemble learning.

XGBoost's core innovations are several. First, it prevents overfitting with a **regularized objective function**. It controls model complexity by applying L1 (Lasso) and L2 (Ridge) regularization to the tree structure. Second, it uses a **second-order Taylor approximation** to optimize the loss function more accurately. Whereas conventional Gradient Boosting used only the first-order derivative (gradient), XGBoost also utilizes the second-order derivative (Hessian).

It is also outstanding in terms of performance optimization. With **histogram-based splitting**, it divides continuous variables into intervals (bins), greatly reducing the amount of computation. With its **Column Block** structure, it stores data in a sorted state, so re-sorting is unnecessary when computing splits. With **Cache-aware Access** and **Out-of-core learning**, it processes large-scale data efficiently as well. It also supports CPU multi-core parallelization and GPU training.

XGBoost supports various tasks such as classification, regression, ranking, and survival analysis, and is compatible with the scikit-learn API. It provides features needed in practice out of the box, such as automatic handling of missing values, early stopping, cross-validation, and feature importance. Together with LightGBM and CatBoost, it is called the "Big 3 of GBDT," and it is still the first choice for tabular data problems.

πŸ’» Code Example

# XGBoost λΆ„λ₯˜ 및 νšŒκ·€ 예제
import xgboost as xgb
import numpy as np
import pandas as pd
from sklearn.datasets import load_breast_cancer, load_diabetes
from sklearn.model_selection import train_test_split, cross_val_score
from sklearn.metrics import accuracy_score, mean_squared_error
import matplotlib.pyplot as plt

# ============================================
# 1. λΆ„λ₯˜ 문제 (Classification)
# ============================================
print("=" * 50)
print("λΆ„λ₯˜ 문제: μœ λ°©μ•” 진단")
print("=" * 50)

# 데이터 λ‘œλ“œ
cancer = load_breast_cancer()
X_clf, y_clf = cancer.data, cancer.target
X_train, X_test, y_train, y_test = train_test_split(
    X_clf, y_clf, test_size=0.2, random_state=42
)

# XGBoost λΆ„λ₯˜κΈ° (scikit-learn API)
clf = xgb.XGBClassifier(
    n_estimators=100,        # 트리 개수
    max_depth=6,             # 트리 μ΅œλŒ€ 깊이
    learning_rate=0.1,       # ν•™μŠ΅λ₯  (eta)
    subsample=0.8,           # ν–‰ μƒ˜ν”Œλ§ λΉ„μœ¨
    colsample_bytree=0.8,    # μ—΄ μƒ˜ν”Œλ§ λΉ„μœ¨
    reg_alpha=0.1,           # L1 μ •κ·œν™”
    reg_lambda=1.0,          # L2 μ •κ·œν™”
    use_label_encoder=False,
    eval_metric='logloss',
    random_state=42
)

# ν•™μŠ΅ (early stopping 포함)
clf.fit(
    X_train, y_train,
    eval_set=[(X_test, y_test)],
    verbose=False
)

# 예츑 및 평가
y_pred = clf.predict(X_test)
accuracy = accuracy_score(y_test, y_pred)
print(f"ν…ŒμŠ€νŠΈ 정확도: {accuracy:.4f}")

# ꡐ차 검증
cv_scores = cross_val_score(clf, X_clf, y_clf, cv=5, scoring='accuracy')
print(f"5-Fold CV 정확도: {cv_scores.mean():.4f} (+/- {cv_scores.std()*2:.4f})")

# ============================================
# 2. νšŒκ·€ 문제 (Regression)
# ============================================
print("\n" + "=" * 50)
print("νšŒκ·€ 문제: 당뇨병 진행도 예츑")
print("=" * 50)

# 데이터 λ‘œλ“œ
diabetes = load_diabetes()
X_reg, y_reg = diabetes.data, diabetes.target
X_train_r, X_test_r, y_train_r, y_test_r = train_test_split(
    X_reg, y_reg, test_size=0.2, random_state=42
)

# XGBoost νšŒκ·€ (Native API - DMatrix μ‚¬μš©)
dtrain = xgb.DMatrix(X_train_r, label=y_train_r)
dtest = xgb.DMatrix(X_test_r, label=y_test_r)

params = {
    'objective': 'reg:squarederror',
    'max_depth': 4,
    'eta': 0.1,
    'subsample': 0.8,
    'colsample_bytree': 0.8,
    'seed': 42
}

# Early stopping으둜 ν•™μŠ΅
evals = [(dtrain, 'train'), (dtest, 'eval')]
model = xgb.train(
    params,
    dtrain,
    num_boost_round=500,
    evals=evals,
    early_stopping_rounds=20,
    verbose_eval=False
)

# 예츑 및 평가
y_pred_r = model.predict(dtest)
rmse = np.sqrt(mean_squared_error(y_test_r, y_pred_r))
print(f"ν…ŒμŠ€νŠΈ RMSE: {rmse:.4f}")
print(f"졜적 반볡 횟수: {model.best_iteration}")

# ============================================
# 3. ν”Όμ²˜ μ€‘μš”λ„ 뢄석
# ============================================
print("\n" + "=" * 50)
print("ν”Όμ²˜ μ€‘μš”λ„ (λΆ„λ₯˜ λͺ¨λΈ)")
print("=" * 50)

# ν”Όμ²˜ μ€‘μš”λ„ (gain, weight, cover)
importance_types = ['weight', 'gain', 'cover']
for imp_type in importance_types:
    importance = clf.get_booster().get_score(importance_type=imp_type)
    if importance:
        sorted_imp = sorted(importance.items(), key=lambda x: x[1], reverse=True)[:5]
        print(f"\n{imp_type.upper()} κΈ°μ€€ Top 5:")
        for feat, score in sorted_imp:
            print(f"  {feat}: {score:.4f}")

# ============================================
# 4. ν•˜μ΄νΌνŒŒλΌλ―Έν„° νŠœλ‹ κ°€μ΄λ“œ
# ============================================
print("\n" + "=" * 50)
print("ν•˜μ΄νΌνŒŒλΌλ―Έν„° νŠœλ‹ κ°€μ΄λ“œ")
print("=" * 50)

tuning_guide = """
1단계: 트리 ꡬ쑰 (과적합 μ œμ–΄)
   - max_depth: 3~10 (κΉŠμ„μˆ˜λ‘ 볡작)
   - min_child_weight: 1~10 (λ†’μ„μˆ˜λ‘ 보수적)

2단계: μƒ˜ν”Œλ§ (λΆ„μ‚° κ°μ†Œ)
   - subsample: 0.6~0.9 (ν–‰ μƒ˜ν”Œλ§)
   - colsample_bytree: 0.6~0.9 (μ—΄ μƒ˜ν”Œλ§)

3단계: μ •κ·œν™” (과적합 λ°©μ§€)
   - reg_alpha (L1): 0~1
   - reg_lambda (L2): 1~10

4단계: ν•™μŠ΅λ₯  및 트리 개수
   - learning_rate: 0.01~0.3
   - n_estimators: learning_rate와 λ°˜λΉ„λ‘€
"""
print(tuning_guide)

πŸ“Š Performance & Cost

Library Training Speed Memory efficiency Categorical variables GPU support
XGBoost Fast Moderate Manual encoding Supported (CUDA)
LightGBM Very fast Excellent Native support Supported
CatBoost Fast Moderate Native support Supported
Random Forest Moderate Excellent Manual encoding Not supported

Performance benchmark (1 million rows, 100 features):

Cost: Free and open source. When using the AWS SageMaker XGBoost built-in, about $0.23 per hour on an ml.m5.xlarge

πŸ—£ How It's Said in Practice

"Since it's tabular data, let's start by running an XGBoost baseline."

-> The basic approach when analyzing tabular data

"Let's apply early stopping to prevent overfitting and extract feature importance."

-> When discussing model training and interpretation

"Try reducing max_depth, lowering learning_rate, and increasing the number of trees."

-> When advising on hyperparameter tuning

"If there are many categorical variables, CatBoost or LightGBM might be better."

-> When discussing library selection

⚠ Common Mistakes & Cautions

Including validation data in the training data

If you put the training data in the eval_set used for early stopping, data leakage occurs. Be sure to use separate validation data.

Ignoring class imbalance

If you do not set the scale_pos_weight parameter on imbalanced data, the model becomes biased toward the majority class. (Set it to the ratio of negative to positive samples.)

Excessive max_depth

If max_depth is too large (10 or more), the risk of overfitting increases sharply. Usually start with a value between 3 and 8.

Correct approach: systematic tuning

1) Check the baseline with default values 2) Tune max_depth and min_child_weight 3) Tune subsample and colsample_bytree 4) Tune regularization (alpha, lambda) 5) Lower learning_rate and increase n_estimators

πŸ”— Related Terms

πŸ“š Learn More