🤖 AI/ML

Ensemble Learning

Ensemble Learning

Combining multiple models to improve performance. Bagging, boosting, stacking.

📖 Detailed Explanation

Ensemble Learning is a machine learning technique that combines multiple individual models (base learners) to achieve better predictive performance than a single model. Similar to the principle of "three men make a tiger (三人成虎)" or "collective intelligence," combining predictions from diverse perspectives can compensate for the weaknesses of individual models and improve generalization performance.

The history of ensemble techniques began in the 1990s with the emergence of Bagging and Boosting. With Leo Breiman's Random Forest in 2001, XGBoost's sweep of Kaggle competitions in 2016, and the emergence of LightGBM and CatBoost in 2017, they became the standard for tabular data analysis. In 2024, hybrid models such as TabNet and TabPFN, which combine deep learning and gradient boosting, are also being actively researched.

The three main ensemble techniques are Bagging, Boosting, and Stacking. Bagging trains independent models in parallel using bootstrap sampling, while Boosting trains sequentially, correcting the errors of previous models. Stacking uses the predictions of first-level models as input to a second-level meta-model to produce the final prediction.

In practice, almost all top solutions in data science competitions such as Kaggle use ensembles. In particular, the "GBDT ensemble," which uses XGBoost, LightGBM, and CatBoost together, shows the highest performance on tabular data and is widely applied to financial fraud detection, recommendation systems, medical diagnosis, and more.

💻 Code Example

# 앙상블 학습 - 스태킹 예제
# pip install scikit-learn xgboost lightgbm catboost

import numpy as np
from sklearn.datasets import make_classification
from sklearn.model_selection import cross_val_score
from sklearn.ensemble import RandomForestClassifier, StackingClassifier
from sklearn.linear_model import LogisticRegression
from xgboost import XGBClassifier
from lightgbm import LGBMClassifier
from catboost import CatBoostClassifier

# 샘플 데이터 생성
X, y = make_classification(n_samples=10000, n_features=20,
                          n_informative=15, random_state=42)

# 1단계: Base Learners 정의
base_learners = [
    ('rf', RandomForestClassifier(n_estimators=100, random_state=42)),
    ('xgb', XGBClassifier(n_estimators=100, random_state=42, verbosity=0)),
    ('lgb', LGBMClassifier(n_estimators=100, random_state=42, verbose=-1)),
    ('cat', CatBoostClassifier(iterations=100, random_state=42, verbose=0))
]

# 2단계: Meta Learner (스태킹)
stacking_clf = StackingClassifier(
    estimators=base_learners,
    final_estimator=LogisticRegression(),
    cv=5,
    stack_method='predict_proba'
)

# 개별 모델 vs 스태킹 성능 비교
print("=== 앙상블 성능 비교 ===")
for name, model in base_learners:
    scores = cross_val_score(model, X, y, cv=5, scoring='accuracy')
    print(f"{name:4s}: {scores.mean():.4f} (+/- {scores.std()*2:.4f})")

# 스태킹 앙상블
stacking_scores = cross_val_score(stacking_clf, X, y, cv=5, scoring='accuracy')
print(f"{'Stack':4s}: {stacking_scores.mean():.4f} (+/- {stacking_scores.std()*2:.4f})")

# 출력 예시:
# rf  : 0.9234 (+/- 0.0156)
# xgb : 0.9312 (+/- 0.0142)
# lgb : 0.9298 (+/- 0.0138)
# cat : 0.9325 (+/- 0.0144)
# Stack: 0.9412 (+/- 0.0128)  <- 스태킹이 개별 모델보다 높은 성능!

📊 Performance & Cost

Comparison of major ensemble algorithms (as of January 2025):

Algorithm Type Features Training Speed
Random Forest Bagging Parallel processing, overfitting prevention Fast (parallel)
XGBoost Boosting Regularization, GPU support Medium
LightGBM Boosting Leaf-wise, large-scale data Very fast
CatBoost Boosting Automatic categorical handling Medium
Stacking Meta Combining diverse models Slow (N times)

🗣️ Say It Like This in Practice

💬 In a Meeting
"A single XGBoost gave an AUC of 0.92, but stacking LightGBM and CatBoost might raise it to 0.95. Inference time will increase threefold, but accuracy matters more in fraud detection."
💬 In an Interview
"The reason ensembles are effective can be explained from the perspective of the Bias-Variance Tradeoff. Bagging reduces variance, and Boosting reduces bias. Combining diverse models can improve both."
💬 In a Technical Discussion
"In Kaggle competitions, almost all winning solutions use ensembles. In production, however, you need to consider inference cost and maintenance complexity. Compressing into a single model with a lightweight Voting ensemble or knowledge distillation is also a good approach."

Take a mock interview on this topic → WIA SOOM AI Interview · Start for free

⚠️ Common Mistakes & Cautions

❌
Ensembling only identical models

Combining multiple instances of the same algorithm leads to insufficient diversity. You need to combine different algorithms, such as Random Forest + XGBoost + LightGBM, to maximize the effect.

❌
Validation data leakage

In stacking, if you train and predict on the same data when generating first-level model predictions, overfitting occurs. Be sure to use Out-of-Fold predictions.

✅
The right way

Use the Out-of-Fold approach, in which a model trained on each fold in K-Fold CV predicts the remaining data. Also, you must finish hyperparameter tuning of the individual models before ensembling.

🔗 Related Terms

📚 Learn More