XGBoost
Extreme Gradient Boosting
An optimized gradient boosting library. A frequent Kaggle winner.
Extreme Gradient Boosting
An optimized gradient boosting library. A frequent Kaggle winner.
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.
# 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)
| 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
"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
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