Decision trees and ensembles
How decision trees choose splits (Gini, entropy), why single trees overfit, and how random forests (bagging) and gradient boosting (XGBoost, LightGBM) combine many trees into the strongest models for tabular data.
For tabular data — spreadsheets of customers, transactions, sensors — tree ensembles are usually the strongest off-the-shelf models, often beating neural networks while needing far less tuning. Credit scoring, fraud detection, churn prediction and many Kaggle competitions are dominated by random forests and gradient-boosted trees such as XGBoost and LightGBM. All of them are built from one simple component: the [[decision-tree|decision tree]][1][2].
How a tree chooses its splits
Starting with all training examples at the root, the algorithm (CART, used by scikit-learn) tries every feature and every threshold, and picks the split that makes the two child nodes purest — i.e. that most reduces an impurity measure. It then repeats recursively on each child until a stopping rule is hit. A leaf predicts the majority class (classification) or the mean target (regression)[1].
- Gini
- Gini impurity: 0 (pure) up to 0.5 for two classes
- Σₖ
- sum over all classes k
- pₖ²
- fraction of class k, squared: chance that two random picks are both class k
- Entropy
- entropy in bits: 0 (pure) up to 1 for two classes
- pₖ
- fraction of examples in the node that belong to class k
- log₂
- logarithm base 2 (log₂ 0.5 = −1). Negative for fractions, hence the leading minus
- MSE
- mean squared error of the targets around the node's mean (= their variance)
▸Worked example
Worked example: a node with 6 ‘yes’ and 4 ‘no’ has Gini 1 − (0.6² + 0.4²) = 0.48. A candidate split sends 5 yes / 0 no left (Gini 0) and 1 yes / 4 no right (Gini 1 − (0.2² + 0.8²) = 0.32). The weighted child impurity is 0.5·0 + 0.5·0.32 = 0.16, so the split reduces impurity by 0.32. The tree picks whichever candidate gives the largest reduction.
Trees are attractive: they handle mixed feature types, need no scaling, capture interactions and non-linearities, and a small tree is easy to explain. Their weakness is high variance: grown fully, a tree keeps splitting until every leaf is pure — memorising noise — and a small change in the data can produce a completely different tree. That is Overfitting in its purest form.
- What it is
- The maximum number of questions from root to leaf.
- ↑ If you increase it
- More complex, finer-grained rules; training error falls toward 0; beyond some depth validation error rises (overfitting). A depth-d tree can have up to 2ᵈ leaves.
- ↓ If you decrease it
- Simpler, more interpretable tree; too shallow (e.g. 1 = a ‘stump’) cannot express the pattern and underfits.
- Typical values
- Single tree: 3–10. Random forest: often unlimited (
None). Gradient boosting: shallow trees, 3–8.
- What it is
- The minimum number of training examples every leaf must contain.
- ↑ If you increase it
- Leaves must summarise more examples, so predictions are smoother and less noise-driven (regularisation); too large → underfits.
- ↓ If you decrease it
- At 1 (default), a leaf can be a single example — maximum flexibility and maximum overfitting risk for a single tree.
- Typical values
- 1–20, or a fraction such as 0.01 of the data for large datasets.
Ensembles: the wisdom of crowds
An ensemble combines many models so their errors partly cancel. There are two main recipes. Bagging trains many deep, independent trees on random variations of the data and averages them — mainly reducing variance. Boosting trains small trees one after another, each fixing the mistakes of the ensemble so far — mainly reducing bias[2].
Random forest (bagging + random features)
A [[random-forest|random forest]] (Breiman, 2001) grows each tree on a bootstrap sample (n rows drawn with replacement, so each tree sees about 63% of the unique rows) and, at every split, considers only a random subset of features. The second trick decorrelates the trees: otherwise they would all split on the same dominant feature and make the same mistakes. Predictions are averaged (regression) or voted (classification)[3]. The rows a tree did not see form its out-of-bag (OOB) set, giving a free validation estimate.
- What it is
- Number of trees in the forest.
- ↑ If you increase it
- Predictions become more stable and accuracy improves, then plateaus. Adding trees does not cause overfitting in a random forest — it only costs time and memory.
- ↓ If you decrease it
- Faster, but predictions are noisier and depend more on the random seed.
- Typical values
- Default 100; 200–1000 is common. Stop adding when the OOB score stops improving.
- What it is
- How many randomly chosen features each split may consider.
- ↑ If you increase it
- Each tree is individually stronger, but trees become more similar (correlated), so averaging helps less. At all features, a forest reduces to plain bagging.
- ↓ If you decrease it
- More diverse, decorrelated trees (lower ensemble variance), but each tree is weaker; too few and important features are rarely available.
- Typical values
- scikit-learn defaults:
"sqrt"(√p features) for classification,1.0(all) for regression. Try 0.3–0.5 for regression.
Gradient boosting
[[gradient-boosting|Gradient boosting]] (Friedman, 2001) builds the model additively. Start with a constant prediction (e.g. the mean). Compute each example's residual — more generally, the negative gradient of the loss. Fit a small tree to those residuals, add a shrunken copy of it to the model, and repeat hundreds of times[4]. It is literally gradient descent in function space: each tree is a step downhill on the loss.
- F₀(x)
- the starting model: a constant, the same for every input
- mean(y)
- the average target in the training set
- rᵢ
- pseudo-residual of example i: the direction and amount the prediction should move
- −∂L(yᵢ, F(xᵢ)) / ∂F
- the negative gradient of the loss with respect to the current prediction F(xᵢ): “which way is downhill for this example”
- yᵢ
- true target of example i
- Fₘ₋₁(xᵢ)
- prediction for example i by the model after m − 1 rounds
- Fₘ(x)
- the model after round m
- Fₘ₋₁(x)
- the model from the previous round
- ν
- nu — Learning rate (shrinkage), typically 0.01–0.3: smaller = more trees needed but better generalisation
- hₘ(x)
- the small Decision tree trained in round m
- r
- the vector of all residuals rᵢ — the tree's training targets
▸Worked example
XGBoost (Chen & Guestrin, 2016) made boosting fast and robust at scale: a regularised objective (penalising the number of leaves and leaf weights), second-order gradient information, sparsity-aware handling of missing values, and efficient parallel, cache-aware split finding[5]. LightGBM, CatBoost and scikit-learn's HistGradientBoosting* use similar ideas, especially histogram binning of features for speed[6].
- What it is
- How much of each new tree's correction is added to the ensemble.
- ↑ If you increase it
- Fewer trees needed and faster training, but each step overshoots more, so the model overfits sooner and generalises worse.
- ↓ If you decrease it
- Smaller, more careful steps usually generalise better, but you need proportionally more trees (halve ν ≈ double the trees).
- Typical values
- 0.01–0.1 (scikit-learn default 0.1; XGBoost default 0.3). Pair a small rate with early stopping.
- What it is
- How many trees are added sequentially (
n_estimatorsin GradientBoosting/XGBoost,max_iterin HistGradientBoosting). - ↑ If you increase it
- Unlike a random forest, boosting can overfit with too many rounds: training loss keeps falling while validation loss turns up.
- ↓ If you decrease it
- Too few rounds leave the residuals uncorrected — underfitting.
- Typical values
- 100–5000 depending on learning rate; set it high and let early stopping on a validation set pick the number.
| Random forest | Gradient boosting | |
|---|---|---|
| Trees built | independently, in parallel | sequentially, each fixing the last |
| Tree size | deep (low bias, high variance) | shallow (high bias, low variance) |
| Mainly reduces | variance | bias |
| More trees → | never hurts accuracy | can overfit; use early stopping |
| Tuning effort | low — good defaults | medium — learning rate, depth, rounds |
| Typical accuracy | very good | often the best on tabular data |
from sklearn.datasets import load_breast_cancer
from sklearn.model_selection import train_test_split
from sklearn.ensemble import RandomForestClassifier, HistGradientBoostingClassifier
from sklearn.inspection import permutation_importance
X, y = load_breast_cancer(return_X_y=True, as_frame=True)
X_tr, X_te, y_tr, y_te = train_test_split(X, y, test_size=0.25, stratify=y, random_state=0)
rf = RandomForestClassifier(n_estimators=500, max_features="sqrt",
oob_score=True, n_jobs=-1, random_state=0).fit(X_tr, y_tr)
print("RF OOB acc:", round(rf.oob_score_, 3), "| test acc:", round(rf.score(X_te, y_te), 3))
gb = HistGradientBoostingClassifier(learning_rate=0.05, max_iter=2000, max_depth=4,
early_stopping=True, validation_fraction=0.1,
n_iter_no_change=20, random_state=0).fit(X_tr, y_tr)
print("GBM rounds used:", gb.n_iter_, "| test acc:", round(gb.score(X_te, y_te), 3))
# Permutation importance on held-out data is more trustworthy than impurity importance
imp = permutation_importance(rf, X_te, y_te, n_repeats=10, random_state=0)
top = imp.importances_mean.argsort()[::-1][:5]
print("top features:", list(X.columns[top]))class_weight or adjust the threshold.▸Go deeper: why averaging decorrelated trees works
If B trees each have variance σ² and pairwise correlation ρ, the variance of their average is:
- Var(average)
- variance of the ensemble's averaged prediction: how much it would jump around between training sets
- ρ
- rho — average correlation between two trees' predictions (0 = independent, 1 = identical)
- σ²
- sigma squared — variance of a single tree's prediction
- B
- number of trees in the ensemble (
n_estimators) - ·
- multiplication
▸Worked example
Adding trees (larger B) kills the second term, but the first term ρσ² remains — so the only way to go lower is to reduce the correlation ρ. That is exactly what random feature subsets do[2]. Boosting has a different lineage: AdaBoost (Freund & Schapire) reweighted misclassified examples; Friedman reinterpreted boosting as gradient descent on a loss, which allowed any differentiable loss[4].
Quiz
References
- [1]scikit-learn User Guide — Decision TreesDocsscikit-learn developersscikit-learn.org
- [2]The Elements of Statistical Learning (2nd ed.) — Ch. 10 Boosting, Ch. 15 Random ForestsBookHastie, Tibshirani & Friedman2009hastie.su.domains
- [3]Random ForestsPaperBreiman2001doi.org
- [4]Greedy Function Approximation: A Gradient Boosting MachinePaperFriedman2001doi.org
- [5]XGBoost: A Scalable Tree Boosting SystemPaperChen & Guestrin2016arxiv.org
- [6]scikit-learn User Guide — Ensembles: gradient boosting, random forests, bagging, voting, stackingDocsscikit-learn developersscikit-learn.org