Skip to content
Tech Atlas, home
Search
Esc
  • All roadmapsBrowse every learning path
  • ExploreFind a technology area
  • ProjectsGuided projects and builds
  • My AtlasYour learning dashboard
Lesson 1 of 6 · Concept · 20 min · revision 2

How a Tree Splits, and Why One Tree Overfits

Compute Gini impurity and the weighted impurity drop of every candidate split by hand, check the result against scikit-learn, see how regression trees use variance, why greedy splitting can miss a good tree, and why a single deep tree memorises noise and changes shape with every new sample.

Contentsand lesson path

What you will learn

  • Explain how a decision tree chooses splits and why bagging (random forests) mainly reduces variance while boosting mainly reduces bias.

01. Why it matters

For tables of numbers and categories, such as customers, transactions or sensor readings, the strongest off-the-shelf models are often tree ensembles: random forests and gradient-boosted trees. Both are built from one simple part, the decision tree. If you know how a single tree chooses its questions and how it fails, the rest of this skill becomes a story about fixing those failures.

A decision tree predicts by asking a sequence of yes-or-no questions about one feature at a time, such as "is monthly_visits at most 5?". Each answer sends a row left or right, and the last node it reaches, a leaf, gives the prediction. In this lesson you compute a split by hand and check it against scikit-learn, see how the same idea works for regression, find a case where the tree-growing method makes a short-sighted choice, and measure why one deep tree overfits. You need Python 3.12, scikit-learn 1.9 and NumPy 2.x. You should already be comfortable with training and validation error from Underfitting, Overfitting and Learning Curves.

02. Impurity: how a split is scored

scikit-learn grows trees with a version of CART (classification and regression trees). At each node it looks for the single question that makes the two child nodes as pure as possible. Impurity measures how mixed the labels in a node are. The usual measure for classification is Gini impurity: one minus the sum of the squared class shares. A node with only one class has Gini 0. A node with half churners and half stayers has Gini 1 − (0.5² + 0.5²) = 0.5, the maximum for two classes. Entropy, the other common choice (criterion="entropy"), measures the same mixing in bits and usually picks very similar splits.

A split is scored by the impurity of its two children, each weighted by its share of the rows, and the tree keeps the split with the largest drop from the parent impurity. The weighting matters: a tiny pure child is easy to make and tells you little about the other rows. The script below does this by hand for ten customers, trying a threshold halfway between each pair of neighbouring values.

Python · split_by_hand.py
import numpy as np
from sklearn.tree import DecisionTreeClassifier

# monthly visits of 10 customers, and whether each one cancelled (1) or stayed (0)
visits = np.array([1, 2, 2, 3, 4, 6, 7, 8, 9, 12])
churned = np.array([1, 1, 0, 1, 1, 0, 0, 1, 0, 0])


def gini(y):
    p = np.bincount(y, minlength=2) / len(y)
    return 1 - np.sum(p**2)


print(f"root: {len(churned)} rows, Gini {gini(churned):.3f}")
print("threshold  left  right  weighted Gini  drop")
values = np.unique(visits)
for t in (values[:-1] + values[1:]) / 2:      # midpoints between sorted values
    left, right = churned[visits <= t], churned[visits > t]
    w = (len(left) * gini(left) + len(right) * gini(right)) / len(churned)
    print(f"{t:9.1f} {len(left):5d} {len(right):6d} {w:14.3f} "
          f"{gini(churned) - w:5.3f}")

stump = DecisionTreeClassifier(max_depth=1).fit(visits.reshape(-1, 1), churned)
print("scikit-learn root threshold:", stump.tree_.threshold[0])
Terminal
python split_by_hand.py
Expected output
root: 10 rows, Gini 0.500
threshold  left  right  weighted Gini  drop
      1.5     1      9          0.444 0.056
      2.5     3      7          0.476 0.024
      3.5     4      6          0.417 0.083
      5.0     5      5          0.320 0.180
      6.5     6      4          0.417 0.083
      7.5     7      3          0.476 0.024
      8.5     8      2          0.375 0.125
     10.5     9      1          0.444 0.056
scikit-learn root threshold: 5.0

The root holds five churners and five stayers, so its Gini is 0.500. The threshold 5.0 sends the first five customers left (four churners, one stayer) and the other five right (one churner, four stayers). Each child has Gini 1 − (0.8² + 0.2²) = 0.32, so the weighted Gini is 0.320 and the drop is 0.180, the best in the table. scikit-learn reaches the same threshold. Look at 8.5 as well: its right child of two stayers is perfectly pure, yet the split scores only 0.125, because that pure child covers just two of the ten rows while the left child of eight stays badly mixed.

A real tree repeats this search over every feature, and over every threshold of each feature, at every node. Then it splits the rows and applies the same search to each child. This is recursive (each child is treated like a new root) and greedy (each split is the best one right now, with no planning for later splits).

03. Regression trees, and the cost of being greedy

For a numeric target, the impurity of a node is the variance of the targets in it (scikit-learn calls the criterion "squared_error"), and a leaf predicts the mean target of its training rows. The split search is the same: try thresholds, weight each child variance by its share of rows, keep the largest drop. The script grows a depth-2 regression tree on two features of the diabetes data that ships with scikit-learn and prints it with export_text.

Python · regression_tree.py
from sklearn.datasets import load_diabetes
from sklearn.tree import DecisionTreeRegressor, export_text

X, y = load_diabetes(return_X_y=True, as_frame=True)
X = X[["bmi", "s5"]]                      # two features keep the printout short
tree = DecisionTreeRegressor(max_depth=2, random_state=0).fit(X, y)
print(export_text(tree, feature_names=list(X.columns), decimals=3))

t = tree.tree_
left, right = t.children_left[0], t.children_right[0]
child = (t.impurity[left] * t.n_node_samples[left]
         + t.impurity[right] * t.n_node_samples[right]) / t.n_node_samples[0]
print(f"root: {t.n_node_samples[0]} rows, variance {t.impurity[0]:.0f}")
print(f"after the root split: {t.n_node_samples[left]} + "
      f"{t.n_node_samples[right]} rows, weighted variance {child:.0f}")
low = y[X["s5"] <= t.threshold[0]]
print(f"mean target of the {len(low)} rows with s5 <= {t.threshold[0]:.3f}: "
      f"{low.mean():.1f}")
Terminal
python regression_tree.py
Expected output
|--- s5 <= -0.004
|   |--- bmi <= 0.006
|   |   |--- value: [96.310]
|   |--- bmi >  0.006
|   |   |--- value: [159.745]
|--- s5 >  -0.004
|   |--- bmi <= 0.015
|   |   |--- value: [162.681]
|   |--- bmi >  0.015
|   |   |--- value: [225.880]

root: 442 rows, variance 5930
after the root split: 218 + 224 rows, weighted variance 4201
mean target of the 218 rows with s5 <= -0.004: 110.0

The root question uses s5 (a blood serum measurement), and it cuts the variance of the targets from 5930 to a weighted 4201. Each of the four leaves predicts one number, the mean of its training rows, so the tree turns a smooth relationship into a staircase of four steps. That staircase is the price of trees: they model sharp thresholds and interactions easily, but they need many splits to follow a smooth trend.

Greediness has a price too. In the next script the label is an XOR pattern: class 1 when exactly one of x0 and x1 is above 0.5. A tree with a root split at x0 <= 0.5 and one split at x1 <= 0.5 on each side would be almost perfect. But on its own, neither feature says anything about the label, so every candidate root split has a Gini drop close to zero.

Python · greedy_xor.py
import numpy as np
from sklearn.tree import DecisionTreeClassifier


def make(n, rng):
    X = rng.uniform(0, 1, size=(n, 2))
    y = ((X[:, 0] > 0.5) ^ (X[:, 1] > 0.5)).astype(int)   # XOR: needs both features
    return X, y


rng = np.random.default_rng(0)
X, y = make(1000, rng)
X_test, y_test = make(5000, rng)
for depth in [1, 2, 3]:
    tree = DecisionTreeClassifier(max_depth=depth, random_state=0).fit(X, y)
    t = tree.tree_
    l, r = t.children_left[0], t.children_right[0]
    drop = t.impurity[0] - (t.impurity[l] * t.n_node_samples[l]
                            + t.impurity[r] * t.n_node_samples[r]) / len(y)
    print(f"max_depth={depth}: root x{t.feature[0]} <= {t.threshold[0]:.3f} "
          f"(Gini drop {drop:.4f}), test accuracy {tree.score(X_test, y_test):.3f}")
Terminal
python greedy_xor.py
Expected output
max_depth=1: root x1 <= 0.986 (Gini drop 0.0030), test accuracy 0.509
max_depth=2: root x1 <= 0.986 (Gini drop 0.0030), test accuracy 0.510
max_depth=3: root x1 <= 0.986 (Gini drop 0.0030), test accuracy 0.979

The root split lands at x1 <= 0.986, a near-useless place chosen because its drop of 0.003 happened to be the largest bit of sampling noise. A depth-2 tree is no better than a coin. Only with a third level can the tree recover the two real splits underneath the wasted root. CART does not look ahead, so it cannot see that a split worth nothing now would be worth a lot one level later. In practice this is one reason deeper trees and ensembles of many trees help: they get more chances to find the pieces of a pattern that no single split reveals.

04. Why one tree overfits

Left alone, scikit-learn keeps splitting until every leaf is pure or cannot be split further. With enough depth a tree can isolate every training row, including rows whose labels are simply wrong. The next script uses make_classification with flip_y=0.1, which flips 10% of labels at random: noise that no model should learn. It compares two depth limits, an unlimited tree, and a tree that requires at least 20 training rows in every leaf (min_samples_leaf=20).

Python · depth_overfit.py
from sklearn.datasets import make_classification
from sklearn.model_selection import train_test_split
from sklearn.tree import DecisionTreeClassifier

# 10% of labels flipped at random: noise that no model should learn
X, y = make_classification(n_samples=2000, n_features=10, n_informative=4,
                           flip_y=0.1, random_state=0)
X_train, X_val, y_train, y_val = train_test_split(X, y, test_size=0.5, random_state=0)

print("setting                 leaves  train acc  val acc")
settings = [("max_depth=2", dict(max_depth=2)), ("max_depth=5", dict(max_depth=5)),
            ("max_depth=None", dict()),
            ("min_samples_leaf=20", dict(min_samples_leaf=20))]
for name, params in settings:
    tree = DecisionTreeClassifier(random_state=0, **params).fit(X_train, y_train)
    print(f"{name:<22} {tree.get_n_leaves():7d} {tree.score(X_train, y_train):10.3f} "
          f"{tree.score(X_val, y_val):8.3f}")
Terminal
python depth_overfit.py
Expected output
setting                 leaves  train acc  val acc
max_depth=2                  4      0.719    0.715
max_depth=5                 24      0.838    0.783
max_depth=None             137      1.000    0.735
min_samples_leaf=20         36      0.818    0.765

Depth 2 underfits: four leaves cannot express the pattern, and training and validation accuracy are both near 0.72. Depth 5 does best on validation (0.783). The unlimited tree grows 137 leaves and reaches 1.000 on training data, which is only possible if it has also fitted the flipped labels; on validation it falls back to 0.735. A minimum leaf size is a gentler limit than a fixed depth, because it stops a branch only where rows run out, and here it scores 0.765. Other controls work the same way: max_leaf_nodes caps the number of leaves, and ccp_alpha prunes branches whose impurity drop is too small to justify them.

Overfitting has a second face, which matters for the next lesson: instability. Because each split depends on the exact rows in a node, a small change in the data can change the root, and then every split below it. The script resamples the same 1,000 training rows five times with replacement and grows a full tree on each sample.

Python · instability.py
import numpy as np
from sklearn.datasets import make_classification
from sklearn.tree import DecisionTreeClassifier

X, y = make_classification(n_samples=2000, n_features=10, n_informative=4,
                           flip_y=0.1, random_state=0)
X_pool, y_pool, X_val = X[:1000], y[:1000], X[1000:]
rng = np.random.default_rng(0)
preds = []
for i in range(5):                   # five resamples of the same 1,000 training rows
    rows = rng.choice(1000, size=1000, replace=True)
    tree = DecisionTreeClassifier(random_state=0).fit(X_pool[rows], y_pool[rows])
    t = tree.tree_
    print(f"sample {i}: root x{t.feature[0]} <= {t.threshold[0]:6.3f}, "
          f"{tree.get_n_leaves()} leaves")
    preds.append(tree.predict(X_val))
pairs = [(i, j) for i in range(5) for j in range(i + 1, 5)]
disagree = np.mean([np.mean(preds[i] != preds[j]) for i, j in pairs])
print(f"two of these trees disagree on {disagree:.1%} of validation rows on average")
Terminal
python instability.py
Expected output
sample 0: root x3 <=  0.281, 98 leaves
sample 1: root x1 <=  0.895, 97 leaves
sample 2: root x3 <=  0.359, 98 leaves
sample 3: root x3 <=  0.464, 96 leaves
sample 4: root x3 <=  0.233, 95 leaves
two of these trees disagree on 25.3% of validation rows on average

Same source, same algorithm, yet the root moves between x3 and x1, its threshold moves from 0.23 to 0.46, and two trees disagree on a quarter of the validation rows. In the language of the bias-variance trade-off, a deep tree has low bias (it can fit almost any shape) and high variance (its predictions depend heavily on which sample it saw). Limiting depth trades some of that variance for bias. The ensembles in the next lesson take two other routes: averaging many deep trees to cancel their variance, or adding many shallow trees one at a time to remove their bias.

05. Check your understanding

Practice check · 3 questions

Reading splits and depth

Answer from the scripts and outputs in this lesson.

Q1. In `split_by_hand.py`, the threshold 8.5 gives a right child of two stayers with Gini 0, yet it scores worse than 5.0. Why?
Q2. In `greedy_xor.py`, the depth-2 tree scores 0.510, although a depth-2 tree splitting at 0.5 on each feature would be almost perfect. What explains this?
Q3. In `depth_overfit.py`, 10% of labels were flipped at random, yet the unlimited tree reaches training accuracy 1.000. What does that tell you?
Practice only: not graded, not saved, not evidence.

06. Apply it

The skill project compares a linear model, a random forest and a tuned boosted model on one tabular dataset. Start it with a single tree.

  1. On your project dataset (or load_breast_cancer), fit DecisionTreeClassifier (or the regressor) with max_depth from 1 to 12 and with no limit, and record training and validation scores. Mark where the tree starts to overfit.
  2. Repeat the five-resample experiment from instability.py on your data and report how often two full trees disagree.
  3. Print the top three levels of your best tree with export_text(tree, max_depth=3) and write two sentences on whether its first questions make sense for the problem.

07. Review prompt

Without looking back, compute the Gini impurity of a node with three positives and one negative; explain why child impurities are weighted by size; say what impurity a regression tree uses and what a leaf predicts; describe a pattern that greedy splitting handles badly; and give two signs that a single tree is overfitting and two settings that limit it.

References

Your progress

Reading state

Sign in to save that you finished reading this lesson.

Sign in to mark reading complete

Prove this skill

8 questions · about 6 minutes · scored automatically. Marking a lesson as read never demonstrates a skill.
Take the skill check