Decision tree pruning

Also known as: tree pruning

On this page 7

Decision tree pruning is the set of techniques that limit or cut back the branches of a decision tree so that the model captures real structure in the data instead of noise. In machine learning, it is the main defense against overfitting in single trees, and it directly controls the bias-variance tradeoff of algorithms such as CART, ID3 and C4.5.

An unpruned tree can keep splitting until every leaf is pure, which often means memorizing the training set. Pruning, also called tree pruning, replaces that fully grown tree with a smaller subtree whose expected error on new data is lower, and which is easier for people to read and audit.

Why unpruned decision trees overfit

Unpruned trees overfit because greedy splitting never stops on its own. Each split is chosen to reduce an impurity measure such as Gini impurity or entropy on the training rows, and almost any split reduces impurity slightly, even one driven by random fluctuations.

Deep branches therefore end in leaves with very few samples, whose predictions rest on a handful of points. The result is low bias but high variance: small changes in the training data produce very different trees and very different predictions.

The table below shows the typical symptoms of a tree that needs pruning.

SymptomLikely causeWhat pruning changes
Near-zero training errorLeaves fit individual samplesMerges noisy leaves
Large train-test gapHigh varianceReduces variance
Hundreds of leavesNo depth or size limitKeeps a compact subtree
Unstable splits across resamplesSplits on noiseRemoves fragile branches
Signs that a tree is overgrown

Pre-pruning and post-pruning

Pruning comes in two families: pre-pruning, which stops growth early, and post-pruning, which grows a large tree first and then removes branches. Pre-pruning is fast and simple, while post-pruning usually finds better subtrees because it can judge a split by what happens below it.

Pre-pruning suffers from the horizon effect. A split that looks useless on its own may enable a very useful split one level deeper, as in the classic XOR pattern, and an early stopping rule never sees that benefit. Post-pruning avoids this problem at the cost of more computation.

The following comparison lists the main controls in each family.

ControlFamilyTypical rangeEffect
Maximum depthPre-pruning3 to 12Caps interaction order
Minimum samples per leafPre-pruning1 to 100 or 1 to 5 percentSmooths leaf estimates
Minimum impurity decreasePre-pruningSmall positive valueBlocks weak splits
Cost-complexity alphaPost-pruningChosen by cross-validationTrades error for size
Reduced error pruningPost-pruningNeeds a validation setRemoves splits that do not help
Common pruning controls

How cost-complexity pruning works

Cost-complexity pruning, also called weakest link pruning, is the post-pruning method of CART. It scores every subtree T with R(T) + α · |T|, where R(T) is the training error or impurity, |T| the number of leaves, and α a complexity parameter that penalizes size.

As α increases from zero, the algorithm repeatedly collapses the internal node whose removal costs the least error per removed leaf. This produces a nested sequence of subtrees, from the full tree down to a single root. Cross-validation then selects α, often with the one-standard-error rule, which picks the smallest tree whose error is within one standard error of the best.

Other post-pruning methods use different criteria, as the table summarizes.

MethodCriterionNeeds held-out dataAssociated algorithm
Cost-complexity pruningError plus size penaltyCross-validationCART
Reduced error pruningValidation accuracyYesGeneric
Pessimistic error pruningUpper confidence bound on errorNoC4.5
Minimum description lengthCode length of tree and errorsNoMDL-based learners
Post-pruning methods compared

In scikit-learn, the parameter ccp_alpha implements this approach, and the method cost_complexity_pruning_path returns the candidate α values, which makes a grid search over the pruning path straightforward.

Pruning in practice and in ensembles

Whether to prune depends on how the tree is used. A single interpretable tree almost always needs pruning, while trees inside ensembles follow different rules because the ensemble itself controls variance.

Use caseRecommended strategyReason
Single explainable treeCost-complexity pruning with cross-validationBest accuracy for its size
Random forestLittle or no pruningAveraging cancels variance
Gradient boostingShallow trees, depth 3 to 8Each tree is a weak learner
Very large datasetsPre-pruning with leaf size limitsKeeps training time low
Regulated scoring modelsStrong pruning plus manual reviewRules must be auditable
Pruning strategy by use case

In random forests, deep trees are deliberate: each tree is individually overfit, and bagging with random feature subsets averages the errors away. Gradient boosting libraries instead rely on depth limits, leaf counts and regularization terms that act as built-in pre-pruning.

Common mistakes when pruning trees

Most pruning errors come from selecting the tree on the wrong data or from tuning one control in isolation. The list below covers frequent problems seen in practice.

  • Choosing α on the test set, which leaks information and inflates reported accuracy.
  • Setting maximum depth alone while leaving tiny leaves allowed, which still overfits in wide trees.
  • Pruning trees inside a random forest and losing ensemble diversity.
  • Ignoring class imbalance, which lets pruning remove the only branches that detect the minority class.
  • Comparing trees by accuracy only, without checking calibration of leaf probabilities.

A reliable workflow fixes a validation protocol first, explores the pruning path, and inspects the final tree for splits that make sense to domain experts. A pruned tree that experts cannot defend is often a sign of data leakage or a spurious feature.

In plain words

A decision tree asks a chain of yes-or-no questions to reach an answer. If it asks too many questions, it starts to remember odd details of past cases. Those details do not help with new cases.

Pruning trims those extra questions, much like a gardener cuts weak shoots from a plant. The tree becomes smaller, clearer and more reliable. It may be slightly less exact on old data, but it predicts new cases better.

A real-world example

A regional hospital builds a decision tree to flag patients at high risk of readmission within 30 days, using about 40,000 past discharges. The fully grown tree reaches 99 percent training accuracy with more than 1,200 leaves, but its validation AUC is only 0.66, and clinicians cannot follow its rules.

The analysts compute the cost-complexity pruning path and run five-fold cross-validation over the candidate α values. Applying the one-standard-error rule, they select a tree with 18 leaves and depth 5. Validation AUC rises to 0.74, and each leaf now covers at least 300 patients. Clinicians review the rules, confirm that splits on prior admissions and medication count are sensible, and the hospital uses the pruned tree as a transparent screening tool alongside nurse assessment.