← All posts

Machine learning algorithms › Tree models

What is a decision tree? How it grows one question at a time

What a decision tree is, how it picks each yes/no question with Gini impurity or entropy, why it overfits and is unstable, and where it fits, with iris data.

If you’ve opened a machine learning course or a scikit-learn tutorial, a decision tree was probably one of the first models you met. The name comes up even more often these days because of the models built on top of it. Random forests and gradient-boosted trees, which scikit-learn’s ensemble guide calls two very famous ensemble methods, are made of many decision trees. XGBoost’s introduction to boosted trees also describes its model as a set of classification and regression trees.

Put in one sentence, a decision tree is a model that predicts by asking a chain of yes/no questions about features, much like a flowchart drawn by hand. A feature is a measurable property of an example, such as the width of a petal, and the label is the answer to predict, such as the species. The first question sits in the root node, each question that divides the data in two is called a split, and the path ends at a leaf node that holds the prediction. scikit-learn’s user guide presents decision trees as a supervised learning method, one that learns from examples whose answers are known, used for both classification and regression.

Growing a tree on the iris flowers

scikit-learn’s iris dataset comes from R.A. Fisher’s 1936 paper. It holds 150 flowers, 50 from each of three species, with the length and width of each flower’s sepals and petals in centimeters. I grew a tree that asks at most two levels of questions and printed it as text with export_text.

from sklearn.datasets import load_iris
from sklearn.tree import DecisionTreeClassifier, export_text

iris = load_iris()
X, y = iris.data, iris.target  # 150 flowers, 4 measurements in cm, 3 species
names = [n.replace(" (cm)", "") for n in iris.feature_names]

tree = DecisionTreeClassifier(max_depth=2, random_state=0).fit(X, y)
print(export_text(tree, feature_names=names,
                  class_names=list(iris.target_names), show_weights=True))
print(f"training accuracy: {tree.score(X, y):.3f}")
print("feature importances:", tree.feature_importances_.round(3))
|--- petal width <= 0.80
|   |--- weights: [50.00, 0.00, 0.00] class: setosa
|--- petal width >  0.80
|   |--- petal width <= 1.75
|   |   |--- weights: [0.00, 49.00, 5.00] class: versicolor
|   |--- petal width >  1.75
|   |   |--- weights: [0.00, 1.00, 45.00] class: virginica

training accuracy: 0.960
feature importances: [0. 0. 0. 1.]

The root asks whether petal width is 0.80 cm or less. If it is, the flower goes to a leaf holding all 50 setosa flowers, and if not, it goes to a second question that splits the rest at 1.75 cm. weights counts the training flowers of each species in a leaf, and the leaf predicts the most common one. So the 5 virginica flowers in the versicolor leaf and the 1 versicolor flower on the other side are the 6 mistakes behind the accuracy of 0.960.

How the tree chooses a question

The tree looks for the question that leaves each side as close to a single species as possible. How mixed a node is gets called impurity, and scikit-learn’s default measure, Gini impurity, is the chance that two flowers drawn at random from the node, with the first put back, are different species. A node with one species scores 0, and at the root, where the three species are mixed equally, it’s two out of three, about 0.667. The other common measure, entropy, is counted in bits. A fair coin flip is 1 bit, three equally likely species are about 1.585 bits, and the drop in entropy a split brings is called information gain.

The tree tries every feature at every midpoint between neighboring values. For each candidate, it averages the impurity of the two sides, weighted by their size, and keeps the question with the biggest drop. Here’s the same search in NumPy.

import numpy as np

def gini(labels):
    p = np.bincount(labels) / len(labels)
    return 1 - np.sum(p ** 2)  # chance two random picks differ

def entropy(labels):
    p = np.bincount(labels) / len(labels)
    return -np.sum(p[p > 0] * np.log2(p[p > 0]))  # in bits

def drop(measure, j, t):  # impurity drop for X[:, j] <= t
    left, right = y[X[:, j] <= t], y[X[:, j] > t]
    return measure(y) - (len(left) * measure(left) + len(right) * measure(right)) / len(y)

found = []
for j, name in enumerate(names):  # every feature, every midpoint
    v = np.unique(X[:, j])
    found += [(drop(gini, j, t), name, t) for t in (v[:-1] + v[1:]) / 2]
for d, name, t in sorted(found, reverse=True)[:2]:
    print(f"{name} <= {t:.2f}: gini drops by {d:.4f}")
print(f"root: gini {gini(y):.4f}, entropy {entropy(y):.4f}")
print(f"information gain of petal width <= 0.80: {drop(entropy, 3, 0.8):.4f}")
print("scikit-learn's node impurities:", tree.tree_.impurity.round(4))
petal width <= 0.80: gini drops by 0.3333
petal length <= 2.45: gini drops by 0.3333
root: gini 0.6667, entropy 1.5850
information gain of petal width <= 0.80: 0.9183
scikit-learn's node impurities: [0.6667 0.     0.5    0.168  0.0425]

The two questions tie, because both set the 50 setosa flowers apart perfectly. The last line shows that scikit-learn also puts the root at 0.6667, the pure left side at 0, and the right side, half versicolor and half virginica, at 0.5. The right side holds two-thirds of the flowers, so the impurity after the split is two-thirds of 0.5, or 0.3333, and 0.6667 minus that gives the same drop of 0.3333 my search found. The DecisionTreeClassifier reference explains that tied splits are picked at random and that random_state fixes the pick. Measured with entropy, the same split gains 0.9183 bits, and with criterion="entropy" the tree chooses its questions by that measure.

Regression trees, which predict a number, follow the same steps. Each leaf predicts the mean of its training values, and the tree picks the question that reduces the squared error around those means the most.

One split at a time, and when to stop

After the root, the tree repeats the search on each side, using only the flowers that reached it. It’s called greedy, because each step takes whatever looks best right now and never goes back, a bit like playing twenty questions by always asking whatever narrows things down most at that moment. The scikit-learn guide explains that finding the best possible tree is NP-complete, a kind of problem with no known fast solution, so practical algorithms settle for the best choice at each node.

By default (max_depth=None), splitting goes on until the leaves are pure, and a tree grown that far tends to memorize noise along with the real pattern. That’s called overfitting. When I grew the iris tree all the way, it used 9 leaves to get every training flower right. Yet in 5-fold cross-validation, which scores the model on each fifth of the data in turn, it got 0.960, no better than the 5-leaf tree at depth 3. Iris is easy, so the gap stays small, but on noisier data it often grows much wider. There are two ways to hold a tree back. One is to stop early with hyperparameters, values you set before training: max_depth limits the depth, and min_samples_leaf sets the fewest examples a leaf may hold. The other is pruning, which cuts back a fully grown tree. scikit-learn’s minimal cost-complexity pruning charges ccp_alpha for every leaf and removes the branches that lower impurity least for each leaf they add. With ccp_alpha=0.01, the tree shrank from 9 leaves to 5 and kept its 0.960.

Leave out ten flowers and the tree changes

The guide also warns that trees can be unstable, since small variations in the data might produce a completely different tree. So I left out 10 random flowers and refit the depth-2 tree, five times over.

for seed in range(5):  # leave out 10 random flowers, five different times
    keep = np.random.default_rng(seed).choice(150, size=140, replace=False)
    t = DecisionTreeClassifier(max_depth=2, random_state=0).fit(X[keep], y[keep])
    node = t.tree_.children_right[0]  # the question asked when the root says "no"
    print(f"seed {seed}: {names[t.tree_.feature[node]]} <= {t.tree_.threshold[node]:.2f}")
seed 0: petal length <= 4.85
seed 1: petal width <= 1.75
seed 2: petal width <= 1.75
seed 3: petal length <= 4.75
seed 4: petal width <= 1.75

With all 150 flowers, the second question was petal width ≤ 1.75. Yet after I removed less than 7% of the data, it moved to petal length in two of the five runs. Every question works only on what the question above it sends down, so a change near the top reshapes everything below. The guide adds that using trees within an ensemble eases this, and a random forest, which grows many trees on resampled data and combines their predictions, rests on the same idea.

Reading feature importance

The last line of the first output came from feature_importances_, which adds up how much impurity each feature’s questions removed, weighted by the number of examples, and scales the totals to sum to 1. Petal width got all of it even though it tied with petal length at the root, but when I refit with random_state=4, the accuracy stayed the same while petal length got 0.562 and petal width 0.438. So it’s safest to read importance as a record of the questions this particular tree happened to ask. The scikit-learn page on permutation importance also cautions that impurity-based importance favors features with many distinct values, and that with an overfit model it can rank highly features that don’t help on new data.

CART, ID3, and C4.5

The scikit-learn guide’s overview of tree algorithms compares the three names you’ll meet most often among algorithms that grow decision trees, roughly like this.

Algorithm Where it comes from How it splits
CART Breiman and three coauthors’ 1984 book Two-way splits, for classification and regression
ID3 Ross Quinlan’s 1986 paper Multiway splits on categorical features by information gain
C4.5 Quinlan’s 1993 book ID3’s successor, also handles numeric features and turns trees into rules

The guide says scikit-learn uses an optimized version of the CART algorithm, so CART is what ran in the examples above. It also notes that the implementation doesn’t support categorical features for now, so categories need to become numbers first.

Where trees fit and where they struggle

Trees fit well when people need to check how a prediction was made. Each prediction is a short path of questions you can print and read, which is why the guide calls them a white box model. And because a question like petal width ≤ 0.80 depends only on the order of the values, trees learn without the data normalization that the guide says other techniques often require. That makes a shallow tree a good first model for a new table of data.

The same way of asking also sets the limits. Each question looks at a single feature, so a tree’s boundaries run parallel to the axes, and a diagonal boundary turns into a staircase. When I labeled 500 random points by a single diagonal line, the full tree used 24 leaves and still scored only 0.962 in cross-validation, short of logistic regression’s 0.984 with one straight line. And since a leaf only returns a mean of values it has seen, the guide says trees are not good at extrapolation, predicting beyond the range they were trained on. I trained a depth-2 regression tree on y = 3x for x between 0 and 10, and at 20 and 100, where the true values are 60 and 300, it answered 26.25 both times, the mean of its last leaf. So if new data may fall outside the training range, as with prices that keep rising, a tree on its own is a risky choice.

If you’re trying it for the first time

I’d suggest running the code blocks above in order and changing one thing at a time. Try criterion="entropy" or change random_state and watch the root question, or follow the guide’s tip and start at max_depth=3 before going deeper. When you want to tune pruning, the cost-complexity pruning example shows how to list candidate ccp_alpha values with cost_complexity_pruning_path. I ran every example here on November 2, 2026, with Python 3.13.12, scikit-learn 1.9.1, and NumPy 2.5.4.

AI tools helped with the research for this post.