Tree Depth, Pruning, and Overfitting
Explore the impact of tree depth and pruning on decision trees to manage overfitting. Understand how deeper trees can memorize training data leading to poor generalization, and how pre-pruning and cost-complexity pruning techniques help create simpler, more reliable models. Learn to evaluate models using training and validation scores, cross-validation, and generalization gaps to select optimal tree settings and improve prediction stability for new data.
A credit-default tree can score 0.99 on the customers used for training and only 0.78 on unseen customers. The training score looks excellent, but the gap shows that the tree learned details that do not repeat for new applicants.
A too-deep tree keeps splitting until small groups of training records receive highly specific rules. Those rules can memorize random variation rather than credit-default patterns that generalize. As with the earlier regression example, training performance is not the goal. We want a tree complex enough to retain predictive signal and simple enough to make stable predictions for new customers.
Use the generalization gap as the diagnostic
Before we restrict a tree, we need evidence that its complexity is the problem. The credit-default data below contains application and account features with a binary default label. Both models train on the same records and face the same held-out test set. The only difference is tree depth.
Lines 8–19: The dataset is generated with a fixed
random_state=42so the train/test accuracy and resulting generalization gap are stable run-to-run, making the depth comparison reproducible.Lines 21–27:
stratify=ypreserves the class balance across train and test splits, so differences in test accuracy are less likely to be an artifact of a skewed split.Lines 29–38: The two classifiers differ only by
max_depth(Nonevs.3), ...