Velamuvi AIAcademy

Lesson 6 of 12 · Core Algorithms

Tree-Based Models

How decision trees learn yes/no questions, how Gini impurity picks each split, and why random forests and gradient boosting beat a single tree on tabular data.

  • 16 min read
  • Intermediate
  • Reviewed
In this lesson you will learn
  • Read the rules a trained decision tree has learned
  • Explain how a tree chooses each question using Gini impurity
  • Describe how random forests and gradient boosting combine many trees
  • Compare a single tree, a forest and boosting with cross-validation
  • Know the strengths and limits of tree-based models, including feature importance

The idea in plain words

A decision tree predicts by asking yes/no questions about the features, one after another, like a flowchart. Each answer leads down a branch, until a leaf gives the prediction. In Introduction to Machine Learning you followed a tree that was written by hand. This lesson shows how a tree learns its questions from labelled data, and why the strongest tree-based models are really teams of trees.

Reading a learned tree

The iris dataset from Regression vs Classification has four measurements per flower. Here is a tree that may ask at most two questions:

Try it yourselfPython
from sklearn.datasets import load_iris
from sklearn.tree import DecisionTreeClassifier, export_text

iris = load_iris()
tree = DecisionTreeClassifier(max_depth=2, random_state=0).fit(iris.data, iris.target)

names = ["sepal length", "sepal width", "petal length", "petal width"]
print(export_text(tree, feature_names=names, class_names=iris.target_names.tolist()))
print("Training accuracy:", round(tree.score(iris.data, iris.target), 3))
Output
|--- petal width <= 0.80
|   |--- class: setosa
|--- petal width >  0.80
|   |--- petal width <= 1.75
|   |   |--- class: versicolor
|   |--- petal width >  1.75
|   |   |--- class: virginica

Training accuracy: 0.96

The tree learned that petal width alone does most of the work: flowers with petals at most 0.80 cm wide are setosa, and a second question at 1.75 cm separates versicolor from virginica. Two questions get 96% of the training flowers right. Because the whole model is a few readable rules, you can check it with an expert, or even copy it into a program as if statements.

How a tree chooses a question

At every step, the tree tries each feature with many possible thresholds, and keeps the question that splits the examples into the purest groups: groups that are mostly one class. Purity is measured with Gini impurity.

Gini = 1 − (share of class 1)² − (share of class 2)² − …

pure group, 6 spam and 0 not spam:   1 − 1.0² − 0.0²  = 0
even group, 5 spam and 5 not spam:   1 − 0.5² − 0.5²  = 0.5

Here is the calculation for one candidate question, "does the email contain a link?", on 10 emails:

Try it yourselfPython
def gini(counts):
    total = sum(counts)
    return 1 - sum((c / total) ** 2 for c in counts)

# 10 emails: 6 spam and 4 not spam. Candidate question: "contains a link?"
parent = [6, 4]
yes, no = [5, 1], [1, 3]          # [spam, not spam] on each side of the split

weighted = (sum(yes) * gini(yes) + sum(no) * gini(no)) / sum(parent)
print(f"Gini before the split: {gini(parent):.3f}")
print(f"Gini of 'yes' side: {gini(yes):.3f}, of 'no' side: {gini(no):.3f}")
print(f"Weighted Gini after the split: {weighted:.3f}  (a drop of {gini(parent) - weighted:.3f})")
Output
Gini before the split: 0.480
Gini of 'yes' side: 0.278, of 'no' side: 0.375
Weighted Gini after the split: 0.317  (a drop of 0.163)

The split's score is the average Gini of its two sides, weighted by how many emails each side holds. The tree computes this drop for every candidate question and keeps the biggest. Then it repeats the whole search inside each branch, and again inside their branches, until a stopping rule such as max_depth says stop. Regression trees work the same way, but measure purity with squared error instead of Gini.

As you saw in Generalisation, a tree that is allowed to keep splitting ends up with a leaf for almost every training example, noise included. Settings such as max_depth and min_samples_leaf (the fewest examples a leaf may hold) keep it in check.

Many trees: random forests

A single deep tree is unstable: change a few training rows and you may get a very different tree. A random forest turns that weakness into a strength:

  1. Each tree is trained on a different random sample of the rows, drawn with replacement (a bootstrap sample).
  2. At each split, each tree may only consider a random subset of the features.
  3. To predict, the trees vote (classification) or their predictions are averaged (regression).

Each tree overfits in its own, different way, and averaging cancels out much of that noise, much as the average guess of a crowd is often better than most individual guesses. This approach is called bagging, short for bootstrap aggregating.

Many trees: gradient boosting

Gradient boosting also uses many trees, but builds them one after another. Each new tree is small, and it is trained to predict the errors that the trees so far still make. Its predictions are added to the running total, usually scaled down by a learning rate so that each tree fixes only part of the remaining error. Here are five rounds of boosting, done by hand:

Try it yourselfPython
import numpy as np
from sklearn.tree import DecisionTreeRegressor

rng = np.random.RandomState(0)
x = rng.uniform(0, 6, size=100).reshape(-1, 1)
y = np.sin(x).ravel() * 10 + rng.normal(0, 1, size=100)

prediction = np.full(100, y.mean())          # round 0: predict the average
print(f"round 0: training MSE {np.mean((y - prediction) ** 2):.2f}")
for round_number in range(1, 6):
    errors = y - prediction                                  # what is still wrong
    small_tree = DecisionTreeRegressor(max_depth=2).fit(x, errors)
    prediction = prediction + 0.5 * small_tree.predict(x)    # fix half of it
    print(f"round {round_number}: training MSE {np.mean((y - prediction) ** 2):.2f}")
Output
round 0: training MSE 49.37
round 1: training MSE 15.94
round 2: training MSE 6.33
round 3: training MSE 3.19
round 4: training MSE 1.96
round 5: training MSE 1.31

Predicting the average gives a training MSE of 49.37. Each small tree (just two questions deep) learns the pattern in the remaining errors, and adding half of its prediction cuts the error again: 15.94, 6.33 and down to 1.31 after five rounds. Real boosting runs hundreds of rounds, so the number of rounds and the learning rate are hyperparameters, chosen with validation to stop before the model starts fitting noise.

In scikit-learn, GradientBoostingClassifier and GradientBoostingRegressor implement this idea, and HistGradientBoostingClassifier and HistGradientBoostingRegressor are much faster versions for large datasets that can also handle missing values. Popular separate libraries such as XGBoost, LightGBM and CatBoost refine it further.

Tree, forest or boosting?

How much do the ensembles help? Here is 5-fold cross-validation on the breast tumour dataset:

Try it yourselfPython
from sklearn.datasets import load_breast_cancer
from sklearn.ensemble import GradientBoostingClassifier, RandomForestClassifier
from sklearn.model_selection import cross_val_score
from sklearn.tree import DecisionTreeClassifier

X, y = load_breast_cancer(return_X_y=True)

models = {
    "one decision tree": DecisionTreeClassifier(random_state=0),
    "random forest, 100 trees": RandomForestClassifier(n_estimators=100, random_state=0),
    "gradient boosting, 50 trees": GradientBoostingClassifier(n_estimators=50, random_state=0),
}
for name, model in models.items():
    scores = cross_val_score(model, X, y, cv=5)
    print(f"{name:<28} accuracy {scores.mean():.3f} +/- {scores.std():.3f}")
Output
one decision tree            accuracy 0.917 +/- 0.016
random forest, 100 trees     accuracy 0.963 +/- 0.022
gradient boosting, 50 trees  accuracy 0.958 +/- 0.017

Both ensembles beat the single tree by about 4 to 5 points. The forest and boosting differ by only 0.005, much less than their spread across folds (about 0.02), so on this dataset they are effectively tied, as you learned to judge in Generalisation. On other datasets, a well-tuned boosting model often comes out slightly ahead, while a forest is harder to get wrong with default settings.

Feature importance

Tree ensembles can report how much each feature helped, by adding up how much that feature's splits reduced impurity across all the trees:

Try it yourselfPython
from sklearn.datasets import load_breast_cancer
from sklearn.ensemble import RandomForestClassifier

data = load_breast_cancer()
forest = RandomForestClassifier(n_estimators=100, random_state=0).fit(data.data, data.target)

ranked = sorted(zip(forest.feature_importances_, data.feature_names), reverse=True)
for importance, name in ranked[:5]:
    print(f"{name:<22} {importance:.3f}")
print(f"(all 30 importances add up to {forest.feature_importances_.sum():.1f})")
Output
worst perimeter        0.174
worst radius           0.122
worst concave points   0.119
mean concave points    0.089
worst area             0.075
(all 30 importances add up to 1.0)

The forest relied most on the size of the largest cell nuclei in each sample (perimeter, radius, area) and on how irregular their outlines are (concave points). Read these numbers with care: perimeter, radius and area are almost the same measurement, so they share credit between them; and importance says what the model used, not what causes a tumour to be malignant. The project lesson uses a more reliable check called permutation importance.

Curved patterns, no scaling

Remember the circle-inside-a-ring data that defeated logistic regression in Linear Models? A tree carves the space into boxes, so it handles curved boundaries without any new features:

Try it yourselfPython
from sklearn.datasets import make_circles
from sklearn.linear_model import LogisticRegression
from sklearn.model_selection import cross_val_score
from sklearn.preprocessing import StandardScaler
from sklearn.tree import DecisionTreeClassifier

X, y = make_circles(n_samples=400, noise=0.1, factor=0.4, random_state=0)
for name, model in [("logistic regression", LogisticRegression()),
                    ("decision tree, depth 4", DecisionTreeClassifier(max_depth=4, random_state=0))]:
    print(f"{name:<23} accuracy {cross_val_score(model, X, y, cv=5).mean():.2f}")

# Rescaling the features changes nothing for a tree
X_scaled = StandardScaler().fit_transform(X)
a = DecisionTreeClassifier(max_depth=4, random_state=0).fit(X, y).predict(X)
b = DecisionTreeClassifier(max_depth=4, random_state=0).fit(X_scaled, y).predict(X_scaled)
print("Same predictions with scaled features:", (a == b).all())
Output
logistic regression     accuracy 0.44
decision tree, depth 4  accuracy 0.97
Same predictions with scaled features: True

The tree scores 0.97 where logistic regression scored 0.44. And scaling makes no difference to a tree, because it only ever compares one feature with a threshold: stretch the feature and the threshold stretches with it.

StrengthsWeaknesses
Learn curved patterns and interactions between features by themselvesA single tree overfits easily and changes a lot with small changes in the data
Need no scaling and little data preparationCan't predict outside the range of the training labels (see Generalisation)
A small tree is easy to read and explainA forest of hundreds of trees can't be read as a whole
Forests and boosting are among the most accurate models for tables of dataLarge ensembles are bigger and slower than linear models

Common mistakes

Practice

Practice exercise

A tree is choosing its first question. Score both candidate splits with the weighted Gini impurity and pick the better one.

Your solutionPython
def gini(counts):
    total = sum(counts)
    return 1 - sum((c / total) ** 2 for c in counts)

# Two candidate questions for 10 emails (6 spam, 4 not spam).
# Each side of a split is [spam, not spam].
candidates = {
    "contains a link?": ([5, 1], [1, 3]),
    "mentions money?": ([4, 0], [2, 4]),
}

# For each question, compute the weighted Gini after the split:
#   (size of yes side x gini(yes) + size of no side x gini(no)) / 10
# Then print the question with the LOWEST weighted Gini, for example:
# Best question: contains a link? (weighted Gini 0.317)
best_question, best_score = "contains a link?", 0.317

print(f"Best question: {best_question} (weighted Gini {best_score:.3f})")
Knowledge check

What is the main difference between a random forest and gradient boosting?

Summary

  • A decision tree predicts by asking yes/no questions; each leaf holds a prediction, and small trees can be read as rules.
  • Each question is chosen greedily to make the groups as pure as possible, measured with Gini impurity (or squared error for regression).
  • A random forest averages many trees trained on random samples of rows and features; gradient boosting adds small trees one by one, each fixing the remaining errors.
  • Ensembles of trees are among the most accurate models for tabular data, need no scaling and learn curved patterns, but can't extrapolate and are hard to read as a whole.
  • Feature importance shows what a model used, not what causes the outcome.

Next: Instance-Based Models, which predict by finding similar examples.

Finished reading? Tick it off to track your progress.