Class 10/Lab: Decision Trees on Breast Tumors
Live in-browser R — edit and re-run any cell
Introduction
Can a few yes/no questions about a tumor’s measurements tell benign from malignant? That is a decision tree. In this lab we use R packages to fit a single tree, prune it, and then improve it with bagging, random forests and boosting. Same data as Lab 9: 569 tumors, 30 features.
Click Run Code on each cell, in order.
Data
We keep 30% of the tumors as a test set.
1. A classification tree
rpart() does recursive binary splitting, choosing each split by the Gini index. We first let it grow a large tree (\(T_0\) in the slides).
2. Pruning
cp is the cost-complexity penalty \(\alpha\) (a larger cp gives a smaller tree). rpart already ran 10-fold CV for each cp while growing the tree. We pick the cp with the lowest CV error (xerror) and prune back to it.
Check: how many leaves does the pruned tree have compared with the large tree? Did test accuracy change?
3. Bagging
Bagging is a random forest in which every split may use all \(p\) features (mtry = p). The package also gives the out-of-bag (OOB) error for free.
4. Random forest
A random forest allows only \(m \approx \sqrt{p}\) randomly chosen features at each split, which decorrelates the trees.
Check: compare the OOB error of bag and rf. Which features matter most?
5. Boosting
Boosting grows trees one after another, each fit to what the previous trees got wrong. n.trees is \(n_B\), shrinkage is \(\lambda\), and interaction.depth controls the size \(d\) of each tree.
6. Compare
Try it yourself
Change mtry in the random forest (try 2, 5, 10, 30). How do the OOB error and test accuracy move?
Things worth remembering
- A tree splits the feature space into regions with recursive binary splitting, and predicts the majority class (or the mean) in each region.
- A large tree overfits. Prune it with cost-complexity pruning, choosing the penalty by cross-validation.
- Bagging averages trees grown on bootstrap samples. The out-of-bag observations give an error estimate with no extra fitting.
- Random forests also sample the features at each split, which decorrelates the trees.
- Boosting grows trees sequentially on the previous errors.
- The ensembles usually predict better than one tree, but they are harder to interpret. Variable importance recovers some of the interpretation.
References
James, G., Witten, D., Hastie, T., and Tibshirani, R. (2021). An Introduction to Statistical Learning (2nd ed.), §8.