🤖 AI/ML

Random Forest

Random Forest

An ensemble technique of many decision trees. Resistant to overfitting.

📖 Detailed Explanation

Random Forest is an ensemble learning method that trains many decision trees and then combines the predictions of each tree to derive the final result. It predicts using majority voting for classification problems and the average value for regression problems, and shows much more stable performance than a single decision tree.

Proposed by Leo Breiman in 2001, Random Forest is an algorithm that combines bagging and feature randomization. Each tree is trained on a bootstrap sample drawn with replacement from the full dataset, and when splitting a node, it considers only a randomly selected subset of features rather than all features. This process reduces the correlation between trees and prevents Overfitting.

The core principle of Random Forest is "the collective intelligence of weak learners." Individual trees tend to overfit, but when hundreds of trees are trained on different data and features, their errors cancel each other out. Feature Importance can be calculated, so Model Interpretability is also excellent, and the OOB (Out-of-Bag) error makes it possible to estimate performance without a separate validation set.

Even in 2024-2025, Random Forest is used as a core algorithm for structured data analysis. Together with XGBoost and LightGBM, it is an essential component of Top 3 solutions in Kaggle competitions, and it is especially preferred in domains where interpretability is important, such as financial fraud detection, medical diagnosis, and credit scoring. scikit-learn's RandomForestClassifier is used more than 100 million times per month.

💻 Code Example

# 랜덤 포레스트 분류 및 피처 중요도 분석
from sklearn.ensemble import RandomForestClassifier
from sklearn.datasets import load_iris
from sklearn.model_selection import train_test_split, cross_val_score
import pandas as pd
import numpy as np

# 데이터 로드
iris = load_iris()
X, y = iris.data, iris.target
feature_names = iris.feature_names

X_train, X_test, y_train, y_test = train_test_split(
    X, y, test_size=0.2, random_state=42
)

# 랜덤 포레스트 모델 생성
rf = RandomForestClassifier(
    n_estimators=100,      # 트리 개수
    max_depth=10,          # 최대 깊이
    min_samples_split=5,   # 분할 최소 샘플
    max_features='sqrt',   # 피처 선택: sqrt(n_features)
    oob_score=True,        # OOB 점수 계산
    random_state=42,
    n_jobs=-1              # 병렬 처리
)

# 학습 및 평가
rf.fit(X_train, y_train)

print(f"테스트 정확도: {rf.score(X_test, y_test):.4f}")
print(f"OOB 점수: {rf.oob_score_:.4f}")

# 교차 검증
cv_scores = cross_val_score(rf, X, y, cv=5)
print(f"5-Fold CV: {cv_scores.mean():.4f} (+/- {cv_scores.std()*2:.4f})")

# 피처 중요도 분석
importance_df = pd.DataFrame({
    'feature': feature_names,
    'importance': rf.feature_importances_
}).sort_values('importance', ascending=False)

print("\n📊 피처 중요도:")
for _, row in importance_df.iterrows():
    bar = '█' * int(row['importance'] * 50)
    print(f"  {row['feature']:20s} {row['importance']:.3f} {bar}")

🗣️ Say It Like This in Practice

💬 In a Meeting
"For a customer churn prediction model, we start with Random Forest. Its interpretability is good, and we can quickly check performance with the OOB score. Looking at feature importance, we can immediately tell which factors affect churn."
💬 In an Interview
"The reason Random Forest is robust against overfitting is bagging and feature randomization. Each tree is trained on a bootstrap sample, and when splitting a node, it considers only sqrt(n_features) features, which reduces the correlation between trees. As a result, variance decreases and generalization performance improves."
💬 In a Technical Discussion
"XGBoost may deliver higher performance, but in regulated industries we prefer Random Forest. Under the EU AI Act, explainability is important. And we can also explain individual predictions by applying SHAP."

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

⚠️ Common Mistakes & Cautions

❌
Just increasing the number of trees (n_estimators) is always better

Beyond 100 trees, the performance gain is marginal and only the training time gets longer. Typically 100-500 is appropriate, so decide based on whether the OOB error has converged.

❌
Using default settings on imbalanced data

Random Forest is biased toward the majority class. You should apply class_weight='balanced' or oversampling such as SMOTE.

✅
The right way

Start with n_estimators=100, control overfitting with max_depth, and adjust class_weight for imbalanced data. Interpret the model with feature importance and SHAP, and validate performance with cross-validation.

🔗 Related Terms

📚 Learn More