AILearn AI
LearnGlossarySources
ID/EN
Learn AI — open material for learning AIEvery lesson cites its original sources.
∿Classical Machine Learning
  1. Linear regression
  2. Gradient descent
  3. Classification: logistic regression, kNN, SVM
  4. Decision trees and ensembles
  5. Clustering and PCA
  6. Overfitting and the bias-variance trade-off
Modules
  1. ◎ AI Foundations
  2. ∿ Classical Machine Learning
  3. ⌬ Neural Networks
  4. ↘ Training Results & Evaluation
  5. ▦ Deep Learning Architectures
  6. ✎ Large Language Models
  7. ◐ Image Generation
  8. ♪ Audio & Speech AI
  9. ◈ Multimodal, Video & 3D
  10. ↻ Reinforcement Learning
  11. ⚙ ML Development & MLOps
  12. ★ Advanced & Frontier Topics
Learn/Classical Machine Learning

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.

Intermediate~28 min·6 references
Key terms
Decision treeRandom forestGradient boostingOverfittingBias-variance trade-offHyperparameterFeature

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].

≈
A game of 20 questions
A decision tree is a flowchart of yes/no questions: ‘Income < 5 million?’ → ‘Has missed a payment before?’ → ‘Loan > 3× income?’ → predict ‘high risk’. A good player asks the question that splits the remaining possibilities most cleanly first. A tree learns which questions to ask, in which order, from the data.

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 = 1 − Σₖ pₖ² Entropy = − Σₖ pₖ · log₂ pₖ Regression: MSE within the node
pₖ = fraction of class k in the node. Both are 0 for a pure node and largest for a 50/50 mix.
In words: Both measure how mixed a node is. Gini reads “the chance that two examples drawn at random from the node have different classes”. Entropy reads “how many yes/no questions (bits) you need on average to guess the class”. Both are 0 for a pure node and largest for an even mix. For regression trees, impurity is simply how spread out the targets are around their mean.
Symbols(hover a symbol in the formula)
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
Node with 6 yes / 4 no → p = 0.6, 0.4 Gini = 1 − (0.36 + 0.16) = 0.48 Entropy = −(0.6·log₂0.6 + 0.4·log₂0.4) ≈ 0.971 bits Split → left 5 yes / 0 no (Gini 0, entropy 0), right 1 yes / 4 no right Gini = 1 − (0.04 + 0.64) = 0.32 right Entropy ≈ 0.722 weighted (5/10 each side): Gini 0.16, entropy ≈ 0.361 reduction: Gini 0.48 − 0.16 = 0.32, entropy 0.971 − 0.361 ≈ 0.610 Regression node with targets [10, 12, 20]: mean 14, MSE = (16 + 4 + 36)/3 ≈ 18.7

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.

knobmax_depth
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.
knobmin_samples_leaf
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.

knobn_estimators (random forest)
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.
knobmax_features
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) = mean(y) rᵢ = −∂L(yᵢ, F(xᵢ)) / ∂F (for MSE: rᵢ = yᵢ − Fₘ₋₁(xᵢ)) Fₘ(x) = Fₘ₋₁(x) + ν · hₘ(x) where hₘ is a small tree fit to r
ν (nu) = learning rate / shrinkage. Each tree corrects a fraction of what is still wrong.
In words: Three lines, three steps. Start by predicting the average for everyone. Then, for every example, compute what is still wrong (the residual — in general the negative Gradient of the loss). Finally train a small tree to predict those residuals and add a fraction ν of it to the model. Repeat for m = 1, 2, …, M: every round removes part of the remaining error.
Symbols(hover a symbol in the formula)
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
y = [10, 20, 30], ν = 0.1, MSE loss F₀ = mean = 20 for all MSE = (100 + 0 + 100)/3 ≈ 66.7 Round 1: r = y − F₀ = [−10, 0, 10] suppose tree h₁ predicts r perfectly: h₁ = [−10, 0, 10] F₁ = 20 + 0.1 · h₁ = [19, 20, 21] MSE = (81 + 0 + 81)/3 = 54 Round 2: r = [−9, 0, 9] → F₂ = [18.1, 20, 21.9] Each round keeps 90% of the residual: after 50 rounds 10 · 0.9⁵⁰ ≈ 0.05 left.

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].

knoblearning_rate (shrinkage ν)
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.
knobn_estimators / boosting rounds
What it is
How many trees are added sequentially (n_estimators in GradientBoosting/XGBoost, max_iter in 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 forestGradient boosting
Trees builtindependently, in parallelsequentially, each fixing the last
Tree sizedeep (low bias, high variance)shallow (high bias, low variance)
Mainly reducesvariancebias
More trees →never hurts accuracycan overfit; use early stopping
Tuning effortlow — good defaultsmedium — learning rate, depth, rounds
Typical accuracyvery goodoften the best on tabular data
python
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]))
A random forest with a free OOB estimate, and histogram gradient boosting with early stopping choosing the number of rounds.
!
Pitfalls
Impurity-based `feature_importances_` are biased toward high-cardinality features (ids, continuous values) — prefer permutation importance or SHAP. Trees cannot extrapolate: a forest trained on prices up to Rp 2 billion will never predict 3 billion. A single deep tree almost always overfits — prune it or use an ensemble. Boosting with a high learning rate and no early stopping overfits quietly. Imbalanced classes: use 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) = ρ·σ² + ((1 − ρ) / B)·σ²
In words: “the noise of an average of B trees = a part that never goes away (the shared, correlated part ρσ²) + a part that shrinks as you add trees”. More trees only kill the second term; to lower the floor you must make the trees less alike (smaller ρ), which is exactly what Random forest feature sampling does.
Symbols(hover a symbol in the formula)
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
σ² = 4 (one tree), ρ = 0.5 B = 1: 0.5·4 + (0.5/1)·4 = 4 (no gain) B = 10: 2 + (0.5/10)·4 = 2.2 B = 100: 2 + (0.5/100)·4 = 2.02 → stuck near the floor ρσ² = 2 Decorrelate to ρ = 0.1, B = 100: 0.1·4 + (0.9/100)·4 = 0.4 + 0.036 = 0.436 (≈ 5× lower)

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

1.
A node contains 5 examples of class A and 5 of class B. What is its Gini impurity?
2.
What happens if you increase n_estimators in a random forest from 100 to 2000?
3.
Why does a random forest consider only a random subset of features at each split?
4.
In gradient boosting with MSE loss, what does each new tree learn to predict?
5.
You lower the boosting learning rate from 0.1 to 0.01 and keep 200 trees. Validation error gets worse. Why?
Score: 0/5

References

  1. [1]
    scikit-learn User Guide — Decision Trees
    Docsscikit-learn developersscikit-learn.org
  2. [2]
    The Elements of Statistical Learning (2nd ed.) — Ch. 10 Boosting, Ch. 15 Random Forests
    BookHastie, Tibshirani & Friedman2009hastie.su.domains
  3. [3]
    Random Forests
    PaperBreiman2001doi.org
  4. [4]
    Greedy Function Approximation: A Gradient Boosting Machine
    PaperFriedman2001doi.org
  5. [5]
    XGBoost: A Scalable Tree Boosting System
    PaperChen & Guestrin2016arxiv.org
  6. [6]
    scikit-learn User Guide — Ensembles: gradient boosting, random forests, bagging, voting, stacking
    Docsscikit-learn developersscikit-learn.org
← Previous
Classification: logistic regression, kNN, SVM
Next →
Clustering and PCA