Sub topic 6
When to stop growing
This chapter assumes you know how a tree picks a split with Gini impurity and information gain, and that you can read basic Python and scikit-learn code. Building on that, it covers the rules that tell a tree to stop splitting and make a node a leaf.
Why a tree needs a stopping rule
Recursive partitioning keeps splitting until something tells it to stop. Without a rule, the tree keeps going until every training sample sits in its own pure leaf. That tree scores 100% on the training data and usually does worse on new data, a problem the next chapter covers in detail.
A stopping criterion is a test run at each node before the tree searches for a split. If the test fires, the node becomes a leaf and predicts the majority class (classification) or the mean target (regression). Stopping rules applied while the tree grows are called pre-pruning or early stopping. Pruning after growth is a separate technique, covered later.
The natural stopping conditions
Two conditions need no tuning. They end growth in any implementation.
- The node is pure. All samples have the same label. No split can lower impurity below zero, so there is nothing to gain.
- No valid split exists. Every sample in the node has identical feature values, or the features cannot separate the samples. Two rows with the same features but different labels can never be separated, so such a node can stay impure forever.
The second case is common in real data with noisy labels or duplicated rows. A tree that stops because of it is limited by the data, not by your settings.
The tunable stopping criteria
The remaining criteria are choices you make to keep the tree small. The table shows the scikit-learn parameter for each.
| Criterion | Parameter | What it checks | Effect when too strict |
|---|---|---|---|
| Maximum depth | `max_depth` | Number of edges from the root to this node | Underfitting. Interactions needing many questions are missed. |
| Minimum samples to split | `min_samples_split` | Samples in the node before splitting | Large nodes stay unsplit. |
| Minimum samples per leaf | `min_samples_leaf` | Samples in each child after the split | Splits that isolate small groups are rejected. |
| Minimum impurity decrease | `min_impurity_decrease` | Weighted gain of the best split | Useful splits that lead to later gains are rejected. |
| Maximum leaves | `max_leaf_nodes` | Total leaf count | Growth stops across the whole tree, not per node. |
How each rule behaves
max_depth is the simplest. A tree of depth 3 asks at most three questions per prediction. It also bounds the size, since a binary tree of depth d has at most 2^d leaves.
min_samples_split is checked on the parent, and min_samples_leaf is checked on the children. A node with 10 samples and min_samples_leaf=6 cannot split at all, because two children cannot both have 6 samples. Of the two, min_samples_leaf is usually the more effective control against overfitting. It guarantees each prediction rests on a minimum amount of evidence. In regression it also keeps leaf means from being computed on one or two noisy points.
min_impurity_decrease compares the weighted gain of the best split against a threshold. In scikit-learn the quantity is:
N_t / N * (impurity - N_t_R / N_t * right_impurity - N_t_L / N_t * left_impurity)Here N is the total number of training samples and Nt is the number in the current node. Because of the Nt / N factor, the same raw improvement counts for less in a small node. A threshold such as 0.01 therefore prunes deep, small nodes more aggressively than shallow, large ones.
max_leaf_nodes changes the growth order. When it is set, scikit-learn grows the tree best-first. It always expands the leaf whose split gives the largest impurity decrease, until the leaf budget runs out. Without it, growth is depth-first.
A stopping check in code
This function runs the checks in a fixed order and reports which one fired. It is a simplified model of what a tree builder does at each node.
def stop_reason(xs, ys, depth, max_depth=3, min_samples_split=4):
if len(set(ys)) == 1:
return "pure node"
if len(set(xs)) == 1:
return "no valid split (identical feature values)"
if depth >= max_depth:
return "max_depth reached"
if len(ys) < min_samples_split:
return "too few samples to split"
return None
cases = [
([1, 2, 3], [0, 0, 0], 0),
([5, 5, 5, 5], [0, 1, 0, 1], 1),
([1, 2, 3, 4, 5, 6], [0, 1, 0, 1, 0, 1], 3),
([1, 2, 3], [0, 1, 1], 1),
([1, 2, 3, 4, 5, 6], [0, 0, 0, 1, 1, 1], 0),
]
for xs, ys, depth in cases:
print(depth, stop_reason(xs, ys, depth) or "keep splitting")The output is:
0 pure node
1 no valid split (identical feature values)
3 max_depth reached
1 too few samples to split
0 keep splittingThe order matters for reporting only. Any rule that fires makes the node a leaf. Checking the cheap conditions first avoids a split search that would be thrown away.
Notice that the last check happens after the split search. Gain and child sizes are properties of a candidate split, so the tree must find the best split before it can reject it.
Effect on a real tree
The next script trains trees with different stopping settings on the iris data. It reports tree size and accuracy on the training and test sets.
from sklearn.datasets import load_iris
from sklearn.model_selection import train_test_split
from sklearn.tree import DecisionTreeClassifier
data = load_iris()
X_train, X_test, y_train, y_test = train_test_split(
data.data, data.target, test_size=0.3, random_state=0, stratify=data.target
)
settings = {
"no limits": {},
"max_depth=2": {"max_depth": 2},
"min_samples_leaf=5": {"min_samples_leaf": 5},
"min_impurity_decrease=0.02": {"min_impurity_decrease": 0.02},
"max_leaf_nodes=4": {"max_leaf_nodes": 4},
}
for name, params in settings.items():
clf = DecisionTreeClassifier(random_state=0, **params).fit(X_train, y_train)
print(
f"{name:28s} depth={clf.get_depth()} leaves={clf.get_n_leaves()} "
f"train={clf.score(X_train, y_train):.3f} test={clf.score(X_test, y_test):.3f}"
)Exact numbers depend on the split and the library version. The pattern to expect is that the unrestricted tree reaches a training accuracy of 1.000 with the most leaves. Each restricted tree has fewer leaves and a slightly lower training score. The test score often stays the same or improves, because the extra leaves of the unrestricted tree mostly fit noise.
Gotchas
Greedy gain can hide a useful split
Stopping on min_impurity_decrease assumes that a split with no immediate gain is worthless. That assumption fails for interactions such as XOR. Suppose the label is 1 when exactly one of two binary features is 1. Splitting on either feature alone leaves both children with the same 50/50 mix as the parent, so the gain is zero. A tree with a positive min_impurity_decrease stops at the root and predicts the majority class. Without the threshold, the tree makes the zero-gain split and the second-level splits separate the classes perfectly.
The lesson is that a gain threshold is a heuristic. A small threshold is safer than a large one, and min_samples_leaf or max_depth do not have this blind spot.
Parameters interact
Several rules often fire at once, and the tightest one wins. Setting max_depth=20 together with min_samples_leaf=30 on a dataset of 200 rows makes the depth limit irrelevant. When you tune, change one criterion at a time or search over them jointly with cross-validation, which a later chapter covers.
Defaults do not stop
In scikit-learn, DecisionTreeClassifier() has max_depth=None, min_samples_split=2, min_samples_leaf=1, and min_impurity_decrease=0.0. This only stops at pure nodes or when no split is possible. It is the maximally overfit configuration, and the right starting point for studying the tree's capacity but rarely for deployment.
Class imbalance and leaf size
A min_samples_leaf value that suits a balanced dataset can wipe out a rare class. If only 15 of 1000 rows are positive and min_samples_leaf=20, no leaf can be built around those positives. Check per-class recall after you set leaf-size limits.
Choosing between pre-pruning and growing then pruning
Stopping early is cheap, because the tree never builds the parts you would discard. Its weakness is the greedy blind spot shown above, which stops growth before a later split pays off. Growing a full tree and then removing weak branches avoids that weakness at higher compute cost. Cost-complexity pruning, covered in a later chapter, is the standard way to do this. In practice many people combine the two: a mild min_samples_leaf to guard against tiny leaves, plus pruning to choose the final size.
Exercise
A tree is trained on 400 rows. At a node with 12 samples, you have set minsamplesleaf=7 and minsamplessplit=2. Can this node split? Explain.
Show answer
No. A split produces two children that must each hold at least 7 samples, which needs at least 14 samples. The node has only 12, so every candidate split violates minsamplesleaf and the node becomes a leaf. minsamplessplit=2 is satisfied, but it does not matter because minsamplesleaf is stricter.
Exercise
On a dataset where the label is the XOR of two binary features, you train one tree with minimpuritydecrease=0.0 and one with minimpuritydecrease=0.05. Which tree can fit the data, and why does the other one fail?
Show answer
The tree with minimpuritydecrease=0.0 can fit it. Splitting on either feature alone leaves both children with the same class mix as the parent, so the first split has zero gain. With a threshold of 0.0 the split is still allowed, and the second-level splits then separate the classes. With 0.05 the root split is rejected because its gain of 0 is below the threshold, so the tree stays a single leaf that predicts the majority class.