Skip to content

Overfit in decision trees: Cost complexity pruning

decision trees are very prone to overfitting.  In fact, a fully grown decision tree is one of the most overfitting models in machine learning.

decision trees are very prone to overfitting. In fact, a fully grown decision tree is one of the most overfitting models in machine learning.

HOW TO DETECT THE OVERFIT?
The train/test split logic works exactly the same for decision trees as it does for neural networks, SVMs, logistic regression, etc.
Decision trees are supervised learning models, so they follow the standard workflow:

Symptoms of an overfitting tree:
• Very deep tree (many levels)
• Many leaves (high complexity)
• Leaves with only 1–2 samples
• Highly irregular / fragmented decision boundaries

 

HOW THE EVALUATION IS DONE ON THE TRAINING AND TEST SETS
You check:
• Accuracy (proportion of test samples the model classifies correctly)
○ Accuracy is good when the classes are balanced.
• F1 ( precision = tp/tp+fp) recall = tp/(tp+fn) f1=2*precision.recall/(precision+recall)
○ used mainly in binary classification (or per-class in multiclass).
○ F1 tells how well the classifier detects the target class, especially when the dataset is unbalanced.F1 tells how well the classifier detects the target class, especially when the dataset is unbalanced.
○ 98% accuracy may be meaningless if the classifier always predicts “negative”.
○ F1 exposes that failure because recall or precision will be near zero.
• MSE (regression)
• etc. (confusion matrix, roc-auc)

All these measures generalization — how well the tree works on unseen data. Accuracy and F1 is for categorical labels, MSE is for numerical labels.

Typical workflow for decision trees
1. Split data into:
○ training set
○ validation set (or use cross-validation)
○ test set
2. Train the tree on the training set.
3. Tune hyperparameters (e.g., max_depth, min_samples_leaf, pruning strength) using validation data.
4. Evaluate final model on the test set only once.

How to prevent overfitting during training

1. Limit tree depth
Most common:
• max_depth = 3, 5, 10, etc.
2. Minimum samples per leaf
E.g.
• min_samples_leaf = 5
• min_samples_split = 10
3. Limit number of leaves
max_leaf_nodes = 20, etc.
4. Prune the tree (post-pruning)
Cut off branches that do not reduce validation error.
CART uses cost-complexity pruning.
5. Bagging / Random Forests
Averaging many trees reduces overfitting dramatically.
6. Boosting
Boosted trees (XGBoost, LightGBM, CatBoost) naturally include regularization.

 

CART’s built-in regularization: Cost-Complexity Pruning

1. Grow a large tree

CART first grows a large tree \(T_0\) on the training data:

  • Continue splitting until nodes are pure, too small, or no valid split remains.
  • Avoid restrictive early-stopping settings.
  • Allow the tree to fit the training data closely, potentially overfitting.

This large tree provides the starting structure from which smaller trees are obtained by pruning.

2. Prune the tree using a regularized cost function

CART defines a regularized loss for the whole tree:

\begin{eqnarray}
R_\alpha(T)&=&R(T)+\alpha|T|,
\end{eqnarray}

where:

  • \(R(T)\) measures the tree’s fit to its training data. Here, we use the weighted Gini impurity of its leaves.
  • \(|T|\) is the number of terminal nodes, or leaves.
  • \(\alpha\geq0\) controls the penalty for tree complexity.

Specifically,

\begin{eqnarray}
R(T)&=&\sum_{\ell\in\mathrm{leaves}(T)}
\frac{N_\ell}{N}\operatorname{Gini}(D_\ell),
\end{eqnarray}

where \(N\) is the total number of training observations and \(N_\ell\) is the number reaching leaf \(\ell\).

This is similar in spirit to ridge or LASSO regularization: \(R(T)\) measures fit, while \(\alpha|T|\) penalizes complexity. Larger values of \(\alpha\) favour smaller trees.

How pruning works

  1. Train the full tree \(T_0\).
  2. Gradually remove the weakest branches: those whose removal increases the training impurity the least per leaf removed.

For each internal node \(t\), let \(T_t\) denote the subtree rooted at that node. Define

\begin{eqnarray}
g(t)&=&\frac{R(t)-R(T_t)}{|T_t|-1},
\end{eqnarray}

where:

  • \(R(T_t)\) is the contribution of the subtree’s leaves to the whole tree’s weighted impurity.
  • \(R(t)\) is the contribution if that subtree is collapsed into a single leaf.
  • \(|T_t|\) is the number of leaves in the subtree.
  • \(|T_t|-1\) is the number of leaves removed by the collapse.

Both impurity contributions use the same whole-tree training-set size \(N\):

\begin{eqnarray}
R(t)&=&\frac{N_t}{N}\operatorname{Gini}(D_t),\
R(T_t)&=&\sum_{\ell\in\mathrm{leaves}(T_t)}
\frac{N_\ell}{N}\operatorname{Gini}(D_\ell).
\end{eqnarray}

The quantity \(g(t)\) is the value of \(\alpha\) at which keeping the subtree and collapsing it have equal regularized cost.

Proceed as follows:

i. Start from the fully grown tree \(T_0\).

ii. Find the weakest link: the internal node \(t\) with the smallest \(g(t)\).

iii. Prune its subtree, replacing it with a leaf. This produces a smaller tree \(T_1\).

iv. Record the corresponding value \(\alpha_1=g(t)\).

v. Recalculate the scores for the remaining internal nodes and repeat, producing \(T_2,T_3,\ldots\) and their associated alpha values.

This generates progressively smaller trees and a nondecreasing sequence:

\begin{eqnarray}
0&\leq&\alpha_1\leq\alpha_2\leq\cdots\leq\alpha_k.
\end{eqnarray}

Equal alpha values can occur. Steps with the same alpha may be grouped together; at a tie, we choose the smaller tree.

3. Choose the pruning strength using cross-validation

Set aside a test set for final evaluation. Split the remaining development data into \(m\) folds (ie, divide the remaining data into \(m\) approximately equal groups, called folds.).

For each fold \(i\):

  • Training data: all development folds except fold \(i\).
  • Validation data: fold \(i\).
  • The held-out test set is not used.

3.1. Construct a pruning sequence for each fold

Train a full tree using that fold’s training data, then prune it. Fold \(i\) produces its own sequence:

\begin{eqnarray}
T_0^{(i)},T_1^{(i)},\ldots,T_{K_i}^{(i)},
\end{eqnarray}

with its own pruning values:

\begin{eqnarray}
0\leq\alpha_1^{(i)}\leq\alpha_2^{(i)}
\leq\cdots\leq\alpha_{K_i}^{(i)}.
\end{eqnarray}

Different folds generally produce different trees, different alpha values, and different sequence lengths.

3.2. Form a common list of candidate alpha values

Collect the alpha values from all folds, include zero, remove duplicates, and sort them. This gives a common candidate list for cross-validation.

3.3. Select the corresponding tree in each fold

For a given candidate \(\alpha\), use the tree obtained after all pruning steps whose breakpoint is at most \(\alpha\).

Equivalently, choose the largest index \(k\) satisfying

\begin{eqnarray}
\alpha_k^{(i)}&\leq&\alpha.
\end{eqnarray}

If no pruning breakpoint satisfies this condition, use the unpruned tree \(T_0^{(i)}\).

Thus, every fold supplies a tree for the same penalty strength \(\alpha\), although those trees may have different numbers of leaves.

3.4. Evaluate the selected trees

For every candidate \(\alpha\) and every fold \(i\):

  • Select the corresponding tree \(T^{(i)}(\alpha)\).
  • Predict the labels of that fold’s validation observations.
  • Calculate the validation misclassification rate.

Call this result \(\operatorname{Err}_i(\alpha)\). Use the predictions learned from the training data; do not reassign leaf labels using validation labels.

For regression trees, the same procedure can use validation MSE.

3.5. Average the validation errors

The results form a table with one row per fold and one column per candidate alpha. Calculate

\begin{eqnarray}\mathrm{CVError}(\alpha)&=&\frac{\mathrm{Error}(1,\alpha)+\cdots+\mathrm{Error}(m,\alpha)}{m}.\end{eqnarray}

This gives a cross-validation error curve indexed by pruning strength.

3.6. Choose alpha

Choose the alpha with the smallest average validation error. If several values tie, prefer the larger alpha, favouring a simpler tree.

An alternative is the one-standard-error rule: choose the simplest candidate whose average validation error is within one estimated standard error of the minimum.

3.7. Fit and evaluate the final tree

Grow a new full tree using all development data, and prune it using the selected alpha.

Finally, evaluate this tree once on the held-out test set. This provides a performance assessment on observations that were used neither to fit the tree nor to choose its pruning strength.

DETAILS

For each internal node \(t\), let \(T_t\) denote the subtree rooted at that node. We want to compare keeping this subtree with collapsing it into one leaf.

Define:

  • \(R(T_t)\): the subtree’s contribution to the whole tree’s training impurity.
  • \(R(t)\): its impurity contribution after collapsing it into one leaf.
  • \(|T_t|\): the number of leaves in the subtree.
  • \(\alpha\): the regularization penalty per leaf.
  • \(C_{\mathrm{rest}}\): the regularized cost contributed by the rest of the tree, which remains unchanged.

Keeping the subtree, its contribution to the regularized cost is

\(C_{\mathrm{keep}}=R(T_t)+\alpha|T_t|.\)

Thus, the whole tree’s cost is

\(C_{\mathrm{total,keep}}=C_{\mathrm{rest}}+C_{\mathrm{keep}}.\)

Collapsing the subtree into one leaf, its contribution becomes

\(C_{\mathrm{prune}}=R(t)+\alpha.\)

The whole tree’s cost becomes

\(C_{\mathrm{total,prune}}=C_{\mathrm{rest}}+C_{\mathrm{prune}}.\)

Since \(C_{\mathrm{rest}}\) is unchanged, the additional cost caused by pruning is

\[ \begin{aligned} C_{\mathrm{total,prune}}-C_{\mathrm{total,keep}} &=C_{\mathrm{prune}}-C_{\mathrm{keep}}\\ &=R(t)-R(T_t)-\alpha(|T_t|-1). \end{aligned} \]

The two choices have equal cost when this difference is zero. Solving for \(\alpha\) gives

\[ \alpha=\frac{R(t)-R(T_t)}{|T_t|-1}. \]

We call this break-even value \(g(t)\):

\[ g(t)=\frac{R(t)-R(T_t)}{|T_t|-1}. \]

If \(\alpha>g(t)\), pruning reduces the total regularized cost. If \(\alpha<g(t)\), keeping the subtree is cheaper.

CART’s built-in regularization: Cost-Complexity Pruning

1. Grow a large tree (overfit on purpose)
CART first grows a maximally large tree T0​:
• split until nodes are pure or too small
• no early stopping
• allow overfitting
This large tree contains all possible splits that might be useful.

2. Prune the tree using a regularized cost function
CART defines a regularized loss:
Rα(T)=R(T)+α∣T∣ //note: this iscalculated for the whole tree T
where:
• R(T) : misclassification error (or Gini) on training/validation set
○ Note that gini of the tree T is the weighted impurity of its leaves
○ Accuracy is the weighted accuracy of its leaves.
• ∣T∣| : number of terminal nodes (leaf count)
• α≥0 : regularization strength
This is identical in spirit to LASSO or ridge regularization:
• R(T) )measures fit to data
• α≥0 penalizes tree complexity

Alpha value of a node vs. alpha value of a tree.

How pruning works (conceptually)
1. Train the full tree T0​.
2. Gradually remove the weakest branches — those whose removal increases impurity of the tree (ie, gini index of the whole tree) the least per leaf removed.
CART defines, for each internal node t with subtree T_t a quantity g(t):
g(t)=(R(t)−R(T_t) / (∣T_t∣−1)​ where
§ R(T_t) : weighted Gini of the whole subtree rooted at ttt
§ R(t ): Weighted Gini if you collapse that subtree into a single leaf
§ ∣T_t∣−1 : number of leaves removed
§ g(t) is the α value corresponding to that prune.
Then:
i. Start from the fully grown tree T_0​.
ii. Find the weakest link: node t with smallest g(t).
iii. Prune the subtree at t (collapse it to a leaf) → get T1​.
iv. Note the α value to that prune → get α1​
v. Repeat on the new tree to get T2,T3,… and α2, α3,…
3. This generates an increasing sequence of alpha values and progressively simpler trees :
0< α1< α2<,….<αk ; T0 ,T1, T2,…, Tk​
4. Split the data into m folds.
For each fold i:
○ Training data = all folds except fold i
○ Validation data = fold i
○ We do not create a separate test set.
1. For each fold: train a full tree T0^(i) and prune it. For fold i you have its own pruning sequence:
T0^(i)​,T1^(i)​,…,Tk_i^(i)​ with its own α-values 0<α1^(i)​<α2^(i)​<⋯<αK_i^​(i)​. Note that T0^(i) is created by using the training part of fold i.
Different folds → different trees → different αk(i) ând different K_i​.
2. Across folds we get many α’s; their union, sorted, gives a global sequence α1,…,αM for CV.
3. How each fold picks a tree for a given global α: In fold i, find the largest k such that
αk^(i)≤α. Then use the ith tree corresponding to αk^(i)
So for each global α, every fold uses some tree from its own sequence that corresponds to that complexity level.
4. For every α in the global list {α1,…,αM}
For every fold i:
Identify the aligned tree: T^(i)(α)=Tk^(i)​,where k=max{k′: αk′^(i)​≤α}
Evaluate that tree on the validation set of fold iii:
–Classification: misclassification error (or cross-entropy, or Gini)
—Regression: MSE, MAE, etc
Call the result: Err_i​(α)
5. You now have an m×M table of validation errors. Average validation error across folds. This produces a cross-validated error curve Err​(α) indexed by tree complexity (α)
6. Choose the α with the smallest average error (there is also 1-se rule):
7. The final tree is obtained by pruning the full tree trained on ALL the data using that α.