Stop 09 · Trees & Ensemble MethodsTopics · 2/8

Tree Pruning & Depth Control

Part of the Machine Learning Roadmap

In short

Left alone, a decision tree keeps asking questions until every leaf holds a single training example. It gets 100% on training data and stumbles on anything new. Pruning is how you stop it memorising.

An unrestricted tree keeps splitting until it memorises the training data. Limits like max_depth, min_samples_leaf and cost-complexity pruning (ccp_alpha) keep trees simpler so they generalise better.

The jaadu stands on a wooden ladder trimming thin overgrown branches from a mango tree with big garden shears, leaves piling on the ground.

Think of it like this

The gardener's shears

A mango tree left to grow wild sprouts hundreds of thin branches that carry tiny, weak fruit. The mali cuts back the extra branches so the tree's strength goes into a few strong ones. Limiting depth is deciding up front how tall it may grow. Cost-complexity pruning is growing it fully, then snipping branches that add little.

Watch it happen

Pruning a loan approval tree

Income > ₹50k?
Has guarantor?
Existing EMIs > 2?
Age = 37?
Approve
Review

1/4The first split on income separates most good and risky applicants.

The big ideas

What you need to know

max_depth

The simplest brake: no path longer than this many questions. Values of 3 to 10 are common starting points.

min_samples_leaf

Every leaf must hold at least this many training rows, so no rule is built on just one or two examples.

ccp_alpha

Cost-complexity pruning grows the full tree, then removes branches whose accuracy gain is not worth their size.

Tune with validation

Plot training and validation score against depth or alpha. Pick the point where validation peaks.

See it in code

Walk through the code

python
1import numpy as np2from sklearn.datasets import load_breast_cancer3from sklearn.model_selection import cross_val_score, train_test_split4from sklearn.tree import DecisionTreeClassifier5 6X, y = load_breast_cancer(return_X_y=True)7X_tr, X_te, y_tr, y_te = train_test_split(X, y, stratify=y, random_state=0)8 9full = DecisionTreeClassifier(random_state=0).fit(X_tr, y_tr)10print("depth", full.get_depth(), "train", full.score(X_tr, y_tr), "test", round(full.score(X_te, y_te), 3))11 12path = full.cost_complexity_pruning_path(X_tr, y_tr)13alphas = path.ccp_alphas[:-1]                     # last alpha prunes to a single node14 15scores = [cross_val_score(DecisionTreeClassifier(random_state=0, ccp_alpha=a), X_tr, y_tr, cv=5).mean()16          for a in alphas]17best_alpha = alphas[int(np.argmax(scores))]18 19pruned = DecisionTreeClassifier(random_state=0, ccp_alpha=best_alpha).fit(X_tr, y_tr)20print("depth", pruned.get_depth(), "test", round(pruned.score(X_te, y_te), 3))

1/4The unpruned tree hits 100% on training data. Note its depth and test score.

Grow a full tree, get the list of useful alphas, and let cross-validation pick how hard to prune.

Save yourself the pain

Common mistakes

Oops

Judging a tree by its training accuracy.

Do this instead

An unpruned tree almost always reaches 100% on training data. Only validation or test scores tell you anything.

Oops

Choosing max_depth by trying values on the test set.

Do this instead

Use cross-validation on training data. Touch the test set once at the very end.

Your mission

Depth vs score

~25 min

Quick check

A tree has 100% training accuracy and 82% test accuracy. Which change is most likely to help?

Go deeper

  1. 1Plot training and validation accuracy as max_depth goes from 1 to 20.
  2. 2Use cost_complexity_pruning_path to find a good ccp_alpha.
  3. 3Compare the size of the pruned and unpruned trees.

More topics at this stop

Stuck on this topic? Ask an Insider

Get 1:1 guidance from people who've walked this exact path — on the InsideEdge app.

Download
InsideEdge