3.2 Tree-Based Models
3.2 Tree-Based Models
Key Concepts
3.2.1 Decision Trees
Decision trees recursively partition the feature space using axis-aligned splits.
Structure
[Age < 30?]
/ \
Yes No
/ \
[Income < 50k?] [Credit Good?]
/ \ / \
Yes No Yes No
/ \ / \
Reject Approve Approve RejectSplitting Criteria
Information Gain (ID3, C4.5):
Based on entropy reduction:
Entropy(S) = -sum(p_i * log2(p_i))
Information Gain = Entropy(parent) - weighted_avg(Entropy(children))
IG(S, A) = H(S) - sum((|S_v| / |S|) * H(S_v))Example:
Parent: 10 samples (6 positive, 4 negative)
H(parent) = -0.6*log2(0.6) - 0.4*log2(0.4) = 0.97 bits
Split on feature A:
Left child: 4 samples (4 pos, 0 neg) -> H = 0
Right child: 6 samples (2 pos, 4 neg) -> H = 0.92
IG = 0.97 - (4/10)*0 - (6/10)*0.92 = 0.42 bitsGini Impurity (CART):
Probability of misclassification:
Gini(S) = 1 - sum(p_i^2)
For binary: Gini = 2 * p * (1-p)Example:
Node with 60% class A, 40% class B:
Gini = 1 - (0.6^2 + 0.4^2) = 1 - 0.52 = 0.48
Pure node (100% one class):
Gini = 1 - 1^2 = 0Comparison:
| Criterion | Range | Computation | Use Case |
|---|---|---|---|
| Entropy | [0, log2(K)] | Slower (log) | Multi-class, information theory |
| Gini | [0, 0.5] for binary | Faster | Default in sklearn, CART |
Both usually give similar results; Gini is computationally cheaper.
Regression Trees
For continuous targets, use variance reduction:
Variance(S) = (1/n) * sum((y_i - mean(y))^2)
Split to minimize weighted variance of childrenPrediction: mean of target values in leaf node.
Stopping Criteria
- Max depth reached
- Min samples per leaf
- Min samples to split
- Max leaf nodes
- Min impurity decrease
- Pure node (all same class)Pruning
Pre-pruning: Stop growing early (max_depth, min_samples)
Post-pruning (Cost-Complexity):
Cost = Error + alpha * |T|
Where:
- Error = misclassification rate
- |T| = number of leaf nodes
- alpha = complexity parameter
Higher alpha -> simpler treePros and Cons
| Pros | Cons |
|---|---|
| Interpretable (if-then rules) | High variance (unstable) |
| No feature scaling needed | Prone to overfitting |
| Handles mixed feature types | Axis-aligned boundaries only |
| Fast inference O(log n) | Greedy, not globally optimal |
| Built-in feature selection | Can't extrapolate |
3.2.2 Ensemble Methods Overview
Combine multiple models to improve performance.
Ensemble Methods
/ \
Bagging Boosting
(parallel) (sequential)
| |
Random Forest Gradient Boosting
/ | \
AdaBoost XGBoost LightGBMWhy Ensembles Work
Bias-Variance Decomposition:
Error = Bias^2 + Variance + Noise
Bagging: Reduces variance (averaging)
Boosting: Reduces bias (sequential correction)Wisdom of Crowds:
If individual models have error rate p < 0.5 and are independent:
P(majority wrong) decreases exponentially with ensemble size
Example: 3 models, each 40% error rate, independent
P(majority wrong) = P(2+ wrong) = 3*0.4^2*0.6 + 0.4^3 = 0.3523.2.3 Bagging (Bootstrap Aggregating)
Train multiple models on bootstrap samples, aggregate predictions.
Algorithm
For b = 1 to B:
1. Draw bootstrap sample D_b (n samples with replacement)
2. Train model h_b on D_b
Prediction:
Classification: majority vote
Regression: averageBootstrap Sampling
Original data: [1, 2, 3, 4, 5]
Bootstrap sample 1: [2, 2, 4, 5, 5] (with replacement)
Bootstrap sample 2: [1, 1, 3, 4, 5]
Bootstrap sample 3: [2, 3, 3, 4, 4]
~63.2% unique samples per bootstrap (1 - 1/e)
~36.8% left out (Out-of-Bag samples)Out-of-Bag (OOB) Error
Free validation without separate holdout:
For each sample x_i:
Predict using only trees where x_i was OOB
OOB Error = average error across all samples
Approximates leave-one-out cross-validationWhy Bagging Reduces Variance
If models have variance sigma^2 and correlation rho:
Var(average of B models) = rho * sigma^2 + (1-rho) * sigma^2 / B
As B -> infinity: Var -> rho * sigma^2
Key insight: Lower correlation -> more variance reduction3.2.4 Random Forest
Bagging + feature randomness for decorrelated trees.
Algorithm
For b = 1 to B:
1. Draw bootstrap sample D_b
2. Train decision tree on D_b:
- At each split, consider only m random features
- m = sqrt(d) for classification
- m = d/3 for regression
3. Grow tree fully (no pruning)
Prediction: majority vote / averageFeature Randomness
Total features: d = 10
At each split, randomly select m = 3 features
Split 1: Consider features [2, 5, 8] -> best is 5
Split 2: Consider features [1, 4, 7] -> best is 1
Split 3: Consider features [3, 6, 9] -> best is 9
Different trees see different feature subsets
-> Trees become decorrelated
-> Averaging is more effectiveHyperparameters
| Parameter | Effect | Typical Values |
|---|---|---|
| n_estimators | More trees = lower variance | 100-1000 |
| max_features | Lower = more randomness | sqrt(d), d/3 |
| max_depth | Deeper = lower bias | None (full) |
| min_samples_leaf | Higher = more regularization | 1-10 |
| bootstrap | Use bootstrap sampling | True |
Feature Importance
Mean Decrease in Impurity (MDI):
Importance(feature j) = sum over all nodes using j of:
(n_samples / total_samples) * impurity_decrease
Averaged across all treesPermutation Importance:
1. Compute baseline score on validation set
2. Shuffle feature j values
3. Recompute score
4. Importance = baseline - shuffled score
More reliable but slower3.2.5 Boosting
Train models sequentially, each correcting predecessor's errors.
General Boosting Framework
Initialize: F_0(x) = constant (e.g., mean for regression)
For m = 1 to M:
1. Compute residuals/pseudo-residuals
2. Fit weak learner h_m to residuals
3. Update: F_m(x) = F_{m-1}(x) + learning_rate * h_m(x)
Final: F_M(x) = sum of all weak learnersAdaBoost (Adaptive Boosting)
Reweight samples based on errors:
Initialize weights: w_i = 1/n
For m = 1 to M:
1. Train classifier h_m on weighted data
2. Compute weighted error:
err_m = sum(w_i * I(y_i != h_m(x_i))) / sum(w_i)
3. Compute model weight:
alpha_m = 0.5 * log((1 - err_m) / err_m)
4. Update sample weights:
w_i = w_i * exp(-alpha_m * y_i * h_m(x_i))
5. Normalize weights
Final: F(x) = sign(sum(alpha_m * h_m(x)))Misclassified samples get higher weights -> next model focuses on them.
Gradient Boosting
Generalize boosting using gradient descent in function space:
Initialize: F_0(x) = argmin_c sum(L(y_i, c))
For m = 1 to M:
1. Compute pseudo-residuals (negative gradient):
r_im = -[dL(y_i, F(x_i)) / dF(x_i)] at F = F_{m-1}
2. Fit regression tree h_m to pseudo-residuals
3. Compute optimal step size:
gamma_m = argmin_gamma sum(L(y_i, F_{m-1}(x_i) + gamma * h_m(x_i)))
4. Update:
F_m(x) = F_{m-1}(x) + learning_rate * gamma_m * h_m(x_i)For MSE Loss:
L = (y - F(x))^2
Pseudo-residual = y - F(x) (actual residual!)For Log Loss (Classification):
L = -[y*log(p) + (1-y)*log(1-p)]
Pseudo-residual = y - p (where p = sigmoid(F(x)))3.2.6 XGBoost (Extreme Gradient Boosting)
Optimized gradient boosting with regularization.
Key Innovations
1. Regularized Objective:
Obj = sum(L(y_i, y_hat_i)) + sum(Omega(f_k))
Omega(f) = gamma * T + 0.5 * lambda * sum(w_j^2)
Where:
- T = number of leaves
- w_j = leaf weights
- gamma = leaf penalty
- lambda = L2 regularization on weights2. Second-Order Approximation:
Obj ≈ sum(g_i * f(x_i) + 0.5 * h_i * f(x_i)^2) + Omega(f)
Where:
- g_i = first derivative of loss
- h_i = second derivative of loss
Enables efficient optimal weight calculation3. Optimal Leaf Weights:
w_j* = -sum(g_i for i in leaf j) / (sum(h_i for i in leaf j) + lambda)4. Split Gain:
Gain = 0.5 * [G_L^2/(H_L+lambda) + G_R^2/(H_R+lambda) - (G_L+G_R)^2/(H_L+H_R+lambda)] - gamma
Where G = sum of gradients, H = sum of hessians
Only split if Gain > 0Computational Optimizations
| Optimization | Description |
|---|---|
| Column block | Pre-sorted data structure for splits |
| Cache-aware | Optimized memory access patterns |
| Out-of-core | Handle data larger than memory |
| Parallel | Parallel tree construction |
| Sparsity-aware | Efficient handling of missing values |
Hyperparameters
| Parameter | Description | Typical Range |
|---|---|---|
| n_estimators | Number of trees | 100-1000 |
| learning_rate (eta) | Shrinkage | 0.01-0.3 |
| max_depth | Tree depth | 3-10 |
| min_child_weight | Min sum of hessian in leaf | 1-10 |
| subsample | Row sampling ratio | 0.5-1.0 |
| colsample_bytree | Column sampling ratio | 0.5-1.0 |
| lambda (reg_lambda) | L2 regularization | 0-10 |
| gamma | Min split gain | 0-5 |
3.2.7 LightGBM
Faster gradient boosting with novel techniques.
Key Innovations
1. Leaf-wise Growth (vs Level-wise):
Level-wise (XGBoost default):
[root]
/ \
[L1] [L1] <- grow all level 1
/ \ / \
[L2] [L2][L2] [L2] <- grow all level 2
Leaf-wise (LightGBM):
[root]
/ \
[L1] [best] <- grow leaf with max gain
/ \
[L2] [L2] <- continue from best leaf
Faster convergence, but risk of overfitting (use max_depth)2. Gradient-based One-Side Sampling (GOSS):
Keep all samples with large gradients (top a%)
Randomly sample from small gradients (b% of rest)
Amplify small gradient samples by (1-a)/b
Reduces data while preserving information3. Exclusive Feature Bundling (EFB):
Bundle mutually exclusive features (rarely non-zero together)
Reduces feature dimension for sparse data
Example: One-hot encoded features can be bundled
[0,1,0,0] + [0,0,1,0] -> single feature with values {1,2}4. Histogram-based Splitting:
Instead of exact splits on all values:
1. Bin continuous features into 256 buckets
2. Build histograms of gradients per bin
3. Find best split from histogram
Much faster: O(#bins) vs O(#data * #features)LightGBM vs XGBoost
| Aspect | XGBoost | LightGBM |
|---|---|---|
| Tree growth | Level-wise | Leaf-wise |
| Speed | Slower | Faster (2-10x) |
| Memory | Higher | Lower |
| Accuracy | Similar | Similar |
| Overfitting risk | Lower | Higher (tune max_depth) |
| Categorical features | Needs encoding | Native support |
3.2.8 CatBoost
Gradient boosting optimized for categorical features.
Key Innovations
1. Ordered Target Statistics:
Problem: Target leakage when encoding categoricals
Solution: For sample i, compute category mean using only samples j < i
(based on random permutation)
Prevents overfitting on categorical features2. Ordered Boosting:
Use different permutations for different trees
Reduces prediction shift (bias from using same data for residuals)3. Symmetric Trees:
All nodes at same depth use same split
Faster inference, acts as regularizationQuestions & Answers
⭐ Q1: How do ensemble methods like bagging and boosting work?
Answer:
Ensemble methods combine multiple models to achieve better performance than any single model.
Bagging (Bootstrap Aggregating):
1. Create B bootstrap samples (sample with replacement)
2. Train independent model on each sample
3. Aggregate predictions:
- Classification: majority vote
- Regression: average
Key properties:
- Models trained in PARALLEL
- Reduces VARIANCE
- Works best with high-variance models (deep trees)Boosting:
1. Start with simple model
2. Sequentially add models that correct previous errors
3. Each model focuses on hard examples
4. Combine with weighted sum
Key properties:
- Models trained SEQUENTIALLY
- Reduces BIAS (and variance)
- Works with weak learners (shallow trees)Comparison:
| Aspect | Bagging | Boosting |
|---|---|---|
| Training | Parallel | Sequential |
| Focus | Reduce variance | Reduce bias |
| Base models | High variance (deep trees) | High bias (stumps) |
| Overfitting | Resistant | Can overfit |
| Example | Random Forest | XGBoost, AdaBoost |
Why they work:
- Bagging: Averaging reduces variance by factor of ~1/B (if uncorrelated)
- Boosting: Sequential correction reduces systematic errors
⭐ Q2: What is the difference between Boosting, Random Forest, and Bootstrap Aggregation?
Answer:
Bootstrap Aggregation (Bagging):
- Sample data with replacement
- Train independent models
- Average/vote predictions
- Reduces variance only
- Any base model worksRandom Forest = Bagging + Feature Randomness:
- Bootstrap sampling (like bagging)
- PLUS: random feature subset at each split
- Decorrelates trees -> more variance reduction
- Uses deep, unpruned trees
- Feature importance built-inBoosting:
- Sequential training
- Each model corrects previous errors
- Weighted combination
- Reduces bias AND variance
- Uses shallow trees (weak learners)Key Differences:
| Aspect | Bagging | Random Forest | Boosting |
|---|---|---|---|
| Sampling | Bootstrap | Bootstrap | Full data (or subsample) |
| Features | All | Random subset | All |
| Training | Parallel | Parallel | Sequential |
| Trees | Deep | Deep | Shallow |
| Main effect | ↓ Variance | ↓↓ Variance | ↓ Bias |
| Correlation | Some | Low (decorrelated) | N/A |
When to use:
- Random Forest: Good default, robust, interpretable importance
- Boosting (XGBoost/LightGBM): Best accuracy, needs tuning
- Plain Bagging: Rarely used alone (RF is better)
Q3: What is the computational difference between XGBoost and Random Forest?
Answer:
Training Complexity:
Random Forest:
- Each tree: O(n * d * log(n)) for n samples, d features
- Total: O(B * n * m * log(n)) where m = features per split
- Fully parallelizable across trees
XGBoost:
- Each tree: O(n * d) with histogram method
- Sequential dependency between trees
- But: parallel within each tree (split finding)Key Computational Differences:
| Aspect | Random Forest | XGBoost |
|---|---|---|
| Parallelism | Embarrassingly parallel | Limited (sequential trees) |
| Split finding | Exact (sort-based) | Approximate (histogram) |
| Memory | Higher (stores all splits) | Lower (histogram bins) |
| Training time | Faster for many trees | Faster per tree |
| Scalability | Linear with trees | Sublinear with data (histogram) |
XGBoost Optimizations:
1. Histogram-based splits: O(#bins) vs O(n)
2. Column block structure: cache-efficient
3. Sparsity-aware: skips missing values
4. Out-of-core: handles large data
5. GPU support: massive speedupPractical Comparison:
Small data (< 10K samples): Similar speed
Medium data (10K-1M): XGBoost often faster
Large data (> 1M): LightGBM fastest, then XGBoost
Random Forest advantages:
- Trivially parallel (use all cores)
- No hyperparameter tuning needed
- More stable trainingQ4: How does gradient boosting handle bias vs variance?
Answer:
Gradient boosting primarily reduces bias, but also affects variance through regularization.
Bias Reduction:
Each tree fits the residual errors of previous trees
-> Systematically corrects underfitting
-> Reduces bias with each iteration
F_m(x) = F_{m-1}(x) + h_m(x)
└─────────┘ └────┘
current model correctionVariance Control:
| Technique | Effect on Variance |
|---|---|
| Learning rate (shrinkage) | Lower rate = lower variance |
| Tree depth | Shallower = lower variance |
| Subsampling | Row/column sampling adds randomness |
| Regularization | L1/L2 on leaf weights |
| Early stopping | Prevents overfitting |
The Tradeoff:
More trees + high learning rate:
-> Low bias, HIGH variance (overfitting)
Fewer trees + low learning rate:
-> Higher bias, lower variance
Optimal: Many trees + low learning rate + early stoppingPractical Strategy:
# Start with:
learning_rate = 0.1
n_estimators = 1000
early_stopping_rounds = 50
# If overfitting: decrease learning_rate, increase regularization
# If underfitting: increase n_estimators, decrease regularizationComparison with Random Forest:
Random Forest:
- High variance base models (deep trees)
- Averaging reduces variance
- Bias stays relatively high
Gradient Boosting:
- Low variance base models (shallow trees)
- Sequential fitting reduces bias
- Regularization controls varianceQ5: How do you choose between Random Forest and Gradient Boosting?
Answer:
Use Random Forest when:
- Need quick baseline with minimal tuning
- Interpretability matters (feature importance)
- Training time is limited
- Want robust, stable model
- Data has many noisy features
- Parallel training resources availableUse Gradient Boosting (XGBoost/LightGBM) when:
- Maximum accuracy is priority
- Have time for hyperparameter tuning
- Data is clean and well-prepared
- Competing in Kaggle :)
- Need to handle missing values natively
- Have categorical features (CatBoost/LightGBM)Decision Framework:
| Factor | Random Forest | Gradient Boosting |
|---|---|---|
| Tuning effort | Low | High |
| Default performance | Good | Needs tuning |
| Best performance | Good | Excellent |
| Training speed | Fast (parallel) | Slower (sequential) |
| Overfitting risk | Low | Higher |
| Missing values | Needs handling | Native support |
| Interpretability | Good | Moderate |
Practical Tips:
1. Start with Random Forest as baseline
2. If need better accuracy, try XGBoost/LightGBM
3. For large data, prefer LightGBM (fastest)
4. For categorical-heavy data, try CatBoost
5. Always use early stopping with boostingQ6: What is information gain and how is it calculated?
Answer:
Information gain measures the reduction in entropy (uncertainty) after splitting on a feature.
Entropy:
H(S) = -sum(p_i * log2(p_i))
- Measures uncertainty/impurity
- H = 0 for pure node (all same class)
- H = 1 for binary with 50-50 splitInformation Gain:
IG(S, A) = H(S) - sum((|S_v| / |S|) * H(S_v))
└──────────────────────────┘
weighted entropy of childrenExample Calculation:
Dataset: 14 samples (9 Yes, 5 No)
H(S) = -9/14 * log2(9/14) - 5/14 * log2(5/14) = 0.940
Split on "Outlook":
Sunny: 5 samples (2 Yes, 3 No) -> H = 0.971
Overcast: 4 samples (4 Yes, 0 No) -> H = 0.000
Rain: 5 samples (3 Yes, 2 No) -> H = 0.971
IG(Outlook) = 0.940 - (5/14)*0.971 - (4/14)*0.000 - (5/14)*0.971
= 0.940 - 0.347 - 0.000 - 0.347
= 0.246 bitsGini Impurity Alternative:
Gini(S) = 1 - sum(p_i^2)
Faster to compute (no logarithm)
Usually gives similar splits
Default in sklearnInterview tip: Know both entropy and Gini, but mention that in practice they rarely differ. Gini is computationally cheaper.