Skip to main content

03 - Decision Trees and Random Forest: How They Work

Compute Gini, entropy and information gain by hand, read a tree's rules, prune it, then see why a random forest is steadier and where importances mislead.

What do you think about this article?

At a Glance

Compute Gini, entropy and information gain by hand, read a tree's rules, prune it, then see why a random forest is steadier and where importances mislead.

A decision tree is a sequence of questions, and it reads like one

A decision tree answers a problem by asking yes/no questions about the variables, one after the other, until it reaches a leaf that holds the prediction. It is the only model in the series that you can print and read like a flowchart, and this matters when you have to explain to a customer why an application was rejected. The price is that a tree left to grow learns the training data by heart: that is why the article tackles trees and random forests together, the technique that puts many trees together to obtain a more stable model. If you come from regression, note the difference: there the boundary between the classes was a line, here it is a staircase of thresholds. The comparison with linear and logistic regression will help you decide which baseline to try first.

Impurity and information gain: how the tree chooses the question

At each node the algorithm tries many "variable, threshold" pairs and chooses the one that makes the two subgroups more pure, that is more dominated by a single class. To measure purity two indexes are needed. The Gini impurity is the probability of being wrong if you assign to an element of the node a label drawn at random according to the proportions of the node. The entropy measures uncertainty in bits: zero if all the elements have the same class, maximum if the classes are balanced. The information gain is the difference between the entropy of the node and the weighted mean of the entropies of the children: how much the question reduced the uncertainty. An everyday example: an urn with 50 red and 50 blue balls is maximum confusion, one with 90 red and 10 blue is already almost decided.

The listing computes both indexes for three nodes and then, on the Iris dataset, the information gain of the threshold "petal length ≤ 2.45 cm", which is the question the scikit-learn tree will open with below. Computing it by hand removes any mystery from the sentence "the tree chooses the best split".

Python - Gini, entropy and information gain computed by hand
import numpy as np
from sklearn.datasets import load_iris

def gini(conteggi):
    p = np.array(conteggi) / np.sum(conteggi)
    return 1 - np.sum(p ** 2)

def entropia(conteggi):
    p = np.array(conteggi) / np.sum(conteggi)
    p = p[p > 0]
    return float(-np.sum(p * np.log2(p))) + 0.0

for nome, c in (("pure node", [50, 0]), ("90 vs 10", [90, 10]), ("50 vs 50", [50, 50])):
    print(f"{nome:14s} gini {gini(c):.3f}  entropy {entropia(c):.3f}")

# Iris: petal length against the species. How much is the threshold 2.45 worth?
iris = load_iris()
petalo = iris.data[:, 2]
y = iris.target
sinistra, destra = y[petalo <= 2.45], y[petalo > 2.45]
c_tot = np.bincount(y)
c_sx, c_dx = np.bincount(sinistra, minlength=3), np.bincount(destra, minlength=3)
peso_sx = len(sinistra) / len(y)
gain = entropia(c_tot) - peso_sx * entropia(c_sx) - (1 - peso_sx) * entropia(c_dx)
print("counts before:", c_tot, "on the left:", c_sx, "on the right:", c_dx)
print(f"entropy before {entropia(c_tot):.3f}, information gain of the threshold 2.45: {gain:.3f}")

# Output:
# pure node      gini 0.000  entropy 0.000
# 90 vs 10       gini 0.180  entropy 0.469
# 50 vs 50       gini 0.500  entropy 1.000
# counts before: [50 50 50] on the left: [50  0  0] on the right: [ 0 50 50]
# entropy before 1.585, information gain of the threshold 2.45: 0.918

The first three lines fix the scales: a pure node has impurity 0 with both indexes, the 90 versus 10 node has Gini 0.180 and entropy 0.469, the 50 versus 50 node has Gini 0.500 and entropy 1.000, the maximum with two classes. The two indexes order the nodes in the same way, so in practice they give almost identical trees, and Gini avoids the logarithm and is a little faster to compute. The last two lines concern Iris: 150 flowers split 50-50-50, entropy 1.585 bits (the maximum with three classes). The threshold 2.45 isolates all 50 setosa on the left and leaves the other two species on the right, with a gain of 0.918 bits out of 1.585: a single question resolves more than half of the uncertainty.

A real tree with scikit-learn, read line by line

scikit-learn implements an optimized version of the CART algorithm: binary trees, thresholds on numerical variables, Gini by default (the criterion parameter also accepts "entropy"). The historical algorithms ID3 and C4.5 used entropy and, unlike CART, admitted categorical variables; the guide warns that the scikit-learn implementation does not support them directly, so they must be encoded first. The listing trains two trees of depth 3 on the Iris dataset, one per criterion, and prints the rules with export_text, which turns the tree into readable text.

Python - Decision tree with Gini and entropy, and its rules
from sklearn.datasets import load_iris
from sklearn.model_selection import train_test_split
from sklearn.tree import DecisionTreeClassifier, export_text

iris = load_iris()
X_train, X_test, y_train, y_test = train_test_split(iris.data, iris.target, test_size=0.2, random_state=42)

for criterio in ("gini", "entropy"):
    albero = DecisionTreeClassifier(criterion=criterio, max_depth=3, random_state=42).fit(X_train, y_train)
    print(f"{criterio}: test accuracy {albero.score(X_test, y_test):.3f}, leaves {albero.get_n_leaves()}")

albero = DecisionTreeClassifier(max_depth=3, random_state=42).fit(X_train, y_train)
print(export_text(albero, feature_names=list(iris.feature_names)))

# Output:
# gini: test accuracy 1.000, leaves 5
# entropy: test accuracy 1.000, leaves 5
# |--- petal length (cm) <= 2.45
# |   |--- class: 0
# |--- petal length (cm) >  2.45
# |   |--- petal length (cm) <= 4.75
# |   |   |--- petal width (cm) <= 1.65
# |   |   |   |--- class: 1
# |   |   |--- petal width (cm) >  1.65
# |   |   |   |--- class: 2
# |   |--- petal length (cm) >  4.75
# |   |   |--- petal width (cm) <= 1.75
# |   |   |   |--- class: 1
# |   |   |--- petal width (cm) >  1.75
# |   |   |   |--- class: 2

Both criteria give the same accuracy (1.000 on the 30-flower test set) and the same number of leaves, five. The text is read from the top: if the petal length is up to 2.45 cm the flower is of class 0 (setosa) and nothing else is asked, which is the threshold computed above. Otherwise the length is looked at again, with threshold 4.75, and then the petal width, with thresholds 1.65 and 1.75, until classes 1 and 2 are told apart. Every path from the root to a leaf is an if/else rule that you can communicate to a non-technical person. As with the forest in the introductory article, the 1.000 on 30 examples says that this split is easy, not that the tree is infallible.

Overfitting and pruning: how far a tree should grow

If you impose no limits, the tree keeps splitting until every leaf is pure, even at the cost of creating a leaf for a single anomalous case. What happens is what we will call overfitting: perfect precision on the training set and worse on the test set, to which article 8 is dedicated. The defenses come in two families. Pre-pruning stops the growth while you build: max_depth limits the levels, min_samples_split the minimum number of examples to split a node, min_samples_leaf the minimum per leaf. Post-pruning builds the full tree and then cuts the branches that are not worth their complexity: scikit-learn offers it with ccp_alpha, cost-complexity pruning, in which a higher value cuts more.

The listing compares four configurations on the breast cancer dataset, reporting leaves, training accuracy and test accuracy. The leaves column is the measure of complexity, and the distance between the two accuracies is the sign of the excessive fit.

Python - Four ways to limit the growth of a tree
from sklearn.datasets import load_breast_cancer
from sklearn.model_selection import train_test_split
from sklearn.tree import DecisionTreeClassifier

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

configurazioni = {
    "no limits": {},
    "max_depth=3": {"max_depth": 3},
    "min_samples_leaf=10": {"min_samples_leaf": 10},
    "ccp_alpha=0.01": {"ccp_alpha": 0.01},
}
for nome, params in configurazioni.items():
    albero = DecisionTreeClassifier(random_state=42, **params).fit(X_train, y_train)
    print(f"{nome:20s} leaves {albero.get_n_leaves():3d}  train {albero.score(X_train, y_train):.3f}  test {albero.score(X_test, y_test):.3f}")

# Output:
# no limits            leaves  16  train 1.000  test 0.947
# max_depth=3          leaves   8  train 0.978  test 0.947
# min_samples_leaf=10  leaves  10  train 0.958  test 0.947
# ccp_alpha=0.01       leaves   7  train 0.980  test 0.956

The tree without limits has 16 leaves and 1.000 on the training set, that is it remembers all 455 examples perfectly, but on the test set it scores 0.947. The three pruned versions have fewer leaves (from 7 to 10), do worse on the training set (from 0.958 to 0.980) and on the test set stay at 0.947, 0.947 and 0.956. The honest message is twofold: pruning did not improve the test score by much, but it obtained the same result with half the complexity, and therefore a more readable and less fragile model. The 0.956 value of cost-complexity pruning is a single case out of 114 more than the others: with such a small test set I would not take it as proof that one method beats the others. To choose ccp_alpha or max_depth seriously you use cross-validation, not the test set.

Random forest: many trees that are wrong in different ways

A single tree is unstable: the scikit-learn guide warns that small variations in the data can produce a completely different tree. A random forest exploits this defect. It trains many trees, each on a random sample with replacement of the data (bootstrap) and, at each split, considering only a random subset of the variables. The trees are wrong at different points, and the majority vote (for classification) or the mean (for regression) cancels part of the errors. The documentation specifies that this reduces the variance "sometimes at the cost of a slight increase in bias", not "without increasing the bias" as is often read. In addition, the samples left out of the bootstrap of a tree serve to evaluate it: the out-of-bag (OOB) estimate is a free evaluation, without a separate validation set.

The listing does three things. It demonstrates the instability, training five trees on as many samples of 80% of the data and printing the question they choose as root. Then it trains a forest of 200 trees with oob_score=True. Finally it compares two ways of measuring the importance of the variables: the one by impurity reduction, which feature_importances_ computes while training, and the one by permutation, which shuffles one test column at a time and measures how much the score drops.

Python - Instability of a tree, forest with OOB, two importance measures
import numpy as np
from sklearn.datasets import load_breast_cancer
from sklearn.ensemble import RandomForestClassifier
from sklearn.inspection import permutation_importance
from sklearn.model_selection import train_test_split
from sklearn.tree import DecisionTreeClassifier

dati = load_breast_cancer()
X_train, X_test, y_train, y_test = train_test_split(dati.data, dati.target, test_size=0.2, random_state=42)

# 1) Instability: the same tree on five different samples of 80% of the data
rng = np.random.default_rng(0)
for _ in range(5):
    idx = rng.choice(len(X_train), size=int(0.8 * len(X_train)), replace=False)
    t = DecisionTreeClassifier(random_state=0).fit(X_train[idx], y_train[idx])
    print(f"root: {dati.feature_names[t.tree_.feature[0]]:22s} threshold {t.tree_.threshold[0]:8.3f}  test {t.score(X_test, y_test):.3f}")

# 2) The forest, with the out-of-bag estimate
rf = RandomForestClassifier(n_estimators=200, oob_score=True, random_state=42).fit(X_train, y_train)
print(f"forest: test {rf.score(X_test, y_test):.3f}  OOB {rf.oob_score_:.3f}")

# 3) Importance: impurity reduction (computed on the train set) against permutation (on the test set)
imp = rf.feature_importances_
perm = permutation_importance(rf, X_test, y_test, n_repeats=20, random_state=0).importances_mean
print("top 5 by impurity:   ", [str(dati.feature_names[i]) for i in np.argsort(imp)[::-1][:5]])
print("top 5 by permutation:", [str(dati.feature_names[i]) for i in np.argsort(perm)[::-1][:5]])
print(f"sum of impurity importances: {imp.sum():.2f}")

# Output:
# root: mean concave points    threshold    0.051  test 0.947
# root: worst radius           threshold   16.795  test 0.895
# root: worst concave points   threshold    0.147  test 0.956
# root: worst radius           threshold   16.795  test 0.939
# root: mean concave points    threshold    0.051  test 0.947
# forest: test 0.965  OOB 0.960
# top 5 by impurity:    ['worst area', 'worst concave points', 'worst perimeter', 'mean concave points', 'worst radius']
# top 5 by permutation: ['worst texture', 'mean texture', 'worst radius', 'worst perimeter', 'worst smoothness']
# sum of impurity importances: 1.00

The five lines on the roots show the problem: the same algorithm on the same data, only with a different sample, chooses three different opening questions (mean concave points, worst radius, worst concave points) and a test accuracy that goes from 0.895 to 0.956. For a model you have to explain, that is bad news. The forest obtains 0.965 on the test set, and the OOB estimate of 0.960, computed on the training set only, is very close: it is the correct use of OOB, an estimate of what to expect before touching the test set. The last three lines say that importance is a less univocal measure than it seems. The five leading variables by impurity are all tied to the size of the nodule (area, perimeter, radius, concave points); by permutation, on the test set, worst texture and mean texture rise instead. It is not a contradiction: the scikit-learn guide explains that the impurity importance is computed on the training set and favors variables with many distinct values, while permutation, on strongly correlated variables such as radius, perimeter and area, underestimates each one because the others compensate. Use them together, and do not discard a variable just because it has a low importance.

When to use them and when not

Trees and forests work well with variables on different scales, because each question looks at one variable at a time and no scaling or normalization is needed, and with nonlinear relationships or interactions between variables, which the tree discovers by itself. They are awkward with very high-dimensional and sparse data, such as text, and with a truly linear signal, where a regression has fewer parameters and reads better. The forest does not predict outside the range seen: a tree ending in leaves that contain training values cannot predict a price higher than the maximum it has met. And it should not be presented as "almost always preferable" to a tree: it loses the readability of the rules, and forces you to go through tools such as importances, with the limits just seen. The natural next step is the comparison between bagging and boosting, of which the forest is the first example.

What you can do now

You can compute impurity and information gain by hand and understand why a tree opens with a given question. You can print the rules of a tree with export_text and read them. You can recognize a tree that memorizes and limit it with max_depth, min_samples_leaf or ccp_alpha, and you know that the test set is used only once, not to choose these parameters. For models that draw boundaries other than the staircase, continue with Support Vector Machines.

For the picture of the paradigms in which tree classification sits, start again from the introduction to the series.

Frequently asked questions

Gini or entropy for a decision tree?

In practice they give almost identical trees: they order the nodes in the same way. Gini avoids the logarithm and is slightly faster, and it is the scikit-learn default; entropy is an alternative selectable with criterion='entropy'.

How do you estimate the error of a random forest without a validation set?

With the out-of-bag estimate: each tree is trained on a bootstrap that leaves out part of the samples, and those samples serve to evaluate it. In scikit-learn it is activated with oob_score=True and read in oob_score_.

How I checked the listings: I ran each one on its own on 2026-11-21 with Python 3.14.4, NumPy 2.3.5 and scikit-learn 1.8.0, and the decimal figures quoted in the text match the ones produced. With other library versions the last digits may change.

Sources

Commenti

Caricamento commenti...

Sign in to comment

New articles and tools on Telegram too

The Telegram channel flags the site's new articles and tools.

Did you like this article?

Explore other content on the blog or discover my projects