
AMOD-5440
Trent University
2026-10-16
We describe trees using the following definitions:
Recall the example of Hitters1 - the Major League Baseball example with characteristics of hitters in MLB in 1986, with their salaries being the response.
Consider the response variable \(\log(\)Salary\()\), and predictor variables Years and Hits.

Roughly speaking, two steps:
Seems simple, right?
Ha. Haha.
The algorithm is called greedy because:
So how does this work in practice?
Next, we are greedy.
At some point, we have to stop, perhaps when no region contains more than some small number (e.g., 5) observations.
Add a penalty, controlled by \(\alpha\), to the cost function for the tree, that is, \[ \sum_{m=1}^{|T|} \sum_{x_i \in R_m} (y_i - \hat{y}_{R_m})^2 + \alpha |T| \] so that we penalize having more nodes (\(|T|\)).
Which model is better? It depends (a statistician’s favourite phrase!).
However, these disadvantages can be overcome by using methods like bagging, random forests and boosting; next, after an example.
Regression tree:
tree(formula = medv ~ ., data = Boston, subset = boston_train)
Variables actually used in tree construction:
[1] "rm" "lstat" "crim" "age"
Number of terminal nodes: 7
Residual mean deviance: 10.38 = 2555 / 246
Distribution of residuals:
Min. 1st Qu. Median Mean 3rd Qu. Max.
-10.1800 -1.7770 -0.1775 0.0000 1.9230 16.5800
Even though the Cross-Validation shows that a 7-node tree minimizes the Cross-Validated RSS, we could still prune the tree:
In interpreting the results of a classification tree, we are often interested not only in the class prediction corresponding to a particular terminal node region, but also in the class proportions among the training observations that fall into that region.
For binary data, this is fairly simple, but it can scale up in complexity when dealing with factor/qualitative multi-level data.
Everything is quite similar to regression trees, except we cannot use RSS in the recursive binary splitting. Instead, we use the classification error rate - the fraction of the training observations in a region that do not belong to the most common class.
\[ 1 - \underset{k}{\text{max}}\left( \hat{p}_{mk} \right) \]
It turns out this isn’t quite sensitive enough for tree-growing, so we use entropy, \[ D = - \sum_{k=1}^{K} \hat{p}_{mk} \log \hat{p}_{mk}. \] to determine the appropriate greedy choice for tree-growing.
We can split qualitative predictors in similar fashion to quantitative ones:
Heart disease data:
Thal (‘Normal’), and the right is the remaining (‘Fixed or Reversible Defects’).Some of the splits result in terminal nodes with the same predicted value.
A simulated data set containing sales of child car seats at 400 different stores. We recode the continuous Sales variable into a binary variable.
Classification tree:
tree(formula = High ~ . - Sales, data = Carseats)
Variables actually used in tree construction:
[1] "ShelveLoc" "Price" "Income" "CompPrice" "Population"
[6] "Advertising" "Age" "US"
Number of terminal nodes: 27
Residual mean deviance: 0.4575 = 170.7 / 373
Misclassification error rate: 0.09 = 36 / 400
The residual mean deviance reported in the above is related to the entropy, with smaller levels indicating trees that provide a good fit to the training data.
There are 27 terminal nodes in this initial fit, which is perhaps a bit high.
We split the observations into a training set and a test set, build the tree using the training set, and evaluate its performance on the test data - around 77% correct.
Confusion Matrix and Statistics
Reference
Prediction No Yes
No 104 33
Yes 13 50
Accuracy : 0.77
95% CI : (0.7054, 0.8264)
No Information Rate : 0.585
P-Value [Acc > NIR] : 2.938e-08
Kappa : 0.5091
Mcnemar's Test P-Value : 0.005088
Sensitivity : 0.6024
Specificity : 0.8889
Pos Pred Value : 0.7937
Neg Pred Value : 0.7591
Prevalence : 0.4150
Detection Rate : 0.2500
Detection Prevalence : 0.3150
Balanced Accuracy : 0.7456
'Positive' Class : Yes
Does pruning the tree give a better result?
The test accuracy is better and the tree is simpler!
Confusion Matrix and Statistics
Reference
Prediction No Yes
No 97 25
Yes 20 58
Accuracy : 0.775
95% CI : (0.7108, 0.8309)
No Information Rate : 0.585
P-Value [Acc > NIR] : 1.206e-08
Kappa : 0.5325
Mcnemar's Test P-Value : 0.551
Sensitivity : 0.6988
Specificity : 0.8291
Pos Pred Value : 0.7436
Neg Pred Value : 0.7951
Prevalence : 0.4150
Detection Rate : 0.2900
Detection Prevalence : 0.3900
Balanced Accuracy : 0.7639
'Positive' Class : Yes
Remember the (very!) brief introduction to the bootstrap we did two weeks ago? Bagging uses the bootstrap to improve decision trees.
The decision trees we discussed earlier suffer from high variance: if we split the data into two parts, completely at random, we could get wildly different predictions from the two halves.
Bootstrap aggregation (b-agg’ing, or bagging), is a procedure for reducing the variance of a statistical learning method, particularly useful for trees.
This process is called bagging.
So far, this process is for quantitative outcomes - regression trees.
In other words, in building a random forest, at each split in the tree, the algorithm is not even allowed to consider a majority of the available predictors.
This may sound crazy, but it has a clever rationale:
Random forests overcome this by forcing each split to consider only a subset of the predictors - making the average less variable, and hence more reliable.
Note that in boosting, unlike in bagging, the construction of each tree depends strongly on the trees that have already been grown.
There are three tuning parameters:
The output of BART is then a set of prediction models for \(1, 2, \cdots, B\). Usually the first few are quite bad, and we throw them out - this is referred to as the burn-in period.
The key advantage to BART over boosting is that because BART tries to improve the results at each step by slightly modifying the previous tree, it guards against overfitting because it limits how “hard” we can fit the data at each iteration. Smaller steps means slower, and slower is typically better.
When we fit a BART model, we have to choose the number of trees, \(K\), the number of iterations, \(B\), and the number of burn-in iterations, \(L\). Usually \(B\) and \(K\) are large, and \(L\) is moderate.
BART is nice because it has very good default performance, and requires minimal tuning usually to give decent predictions.
We set mtry = 12 because there are 12 predictors in the dataset.
Call:
randomForest(formula = medv ~ ., data = Boston, mtry = 12, importance = TRUE, subset = boston_train)
Type of random forest: regression
Number of trees: 500
No. of variables tried at each split: 12
Mean of squared residuals: 11.40162
% Var explained: 85.17
So we have
# A tibble: 2 × 2
method MSE
<chr> <dbl>
1 Bagging 23.4
2 Pruned Tree 35.9
a reduction in MSE by about 1/3: the previous optimally-pruned single tree had a MSE of around 36, and we now have around 23.
If we don’t set mtry to 12, we get an actual random forest model:
# A tibble: 3 × 2
method MSE
<chr> <dbl>
1 Random Forest 20.1
2 Bagging 23.4
3 Pruned Tree 35.9
So choosing from a random selection of 6 variables at each split, we get a random forest which slightly improves on the previous test MSE of the bagging model above.
We can look at the importance of each variable:
%IncMSE IncNodePurity
crim 19.435587 1070.42307
zn 3.091630 82.19257
indus 6.140529 590.09536
chas 1.370310 36.70356
nox 13.263466 859.97091
rm 35.094741 8270.33906
age 15.144821 634.31220
dis 9.163776 684.87953
rad 4.793720 83.18719
tax 4.410714 292.20949
ptratio 8.612780 902.20190
lstat 28.725343 5813.04833
We can also plot, showing lstat (wealth) and rm (house size) are by far the most important.
Another new package, gbm.
var rel.inf
rm rm 44.936598303
lstat lstat 29.812159051
crim crim 6.103055959
dis dis 4.762815179
nox nox 4.335382715
age age 3.761324798
tax tax 2.288495519
ptratio ptratio 2.279678246
indus indus 0.953981946
rad rad 0.632964710
zn zn 0.131312988
chas chas 0.002230587
Again, lstat and rm are the most important variables by far. We can plot the partial dependence plot, which shows that medv (median house prices) are increasing with rm.
Median house prices decrease with lstat.
Using cross-validation, the best iteration was 361 trees.
gbm(formula = medv ~ ., distribution = "gaussian", data = Boston[boston_train,
], n.trees = 5000, interaction.depth = 4, cv.folds = 10)
A gradient boosted model with gaussian loss function.
5000 iterations were performed.
The best cross-validation iteration was 361.
There were 12 predictors of which 11 had non-zero influence.
# A tibble: 4 × 2
method MSE
<chr> <dbl>
1 Boosting 17.3
2 Random Forest 20.1
3 Bagging 23.4
4 Pruned Tree 35.9
Significant improvement again, over both bagging and random forest.
*****Calling gbart: type=1
*****Data:
data:n,p,np: 253, 12, 253
y1,yn: 0.213439, -5.486561
x1,x[n*p]: 0.109590, 20.080000
xp1,xp[np*p]: 0.027310, 7.880000
*****Number of Trees: 200
*****Number of Cut Points: 100 ... 100
*****burn,nd,thin: 100,1000,1
*****Prior:beta,alpha,tau,nu,lambda,offset: 2,0.95,0.795495,3,3.71636,21.7866
*****sigma: 4.367914
*****w (weights): 1.000000 ... 1.000000
*****Dirichlet:sparse,theta,omega,a,b,rho,augment: 0,0,1,0.5,1,12,0
*****printevery: 100
MCMC
done 0 (out of 1100)
done 100 (out of 1100)
done 200 (out of 1100)
done 300 (out of 1100)
done 400 (out of 1100)
done 500 (out of 1100)
done 600 (out of 1100)
done 700 (out of 1100)
done 800 (out of 1100)
done 900 (out of 1100)
done 1000 (out of 1100)
time: 1s
trcnt,tecnt: 1000,1000
We can check how many times each variable appeared in the collection of trees.
nox lstat rad rm tax ptratio chas age indus zn
22.973 21.653 21.638 20.725 20.021 19.615 19.283 19.278 19.073 15.576
dis crim
13.800 11.607
Recall that BART is randomizing the selection, to try to ensure we don’t overfit. Notice how rm and lstat are not the highest, despite being the most important predictors by far in the earlier model? This is BART acting to keep us from overfitting by forcing all models to start with these two.
We can compute the error, again:
# A tibble: 5 × 2
method MSE
<chr> <dbl>
1 BART 15.9
2 Boosting 17.3
3 Random Forest 20.1
4 Bagging 23.4
5 Pruned Tree 35.9
So on this data set, the BART result is the best for MSE on the test data.
Trees are an attractive choice of weak learner for an ensemble method for a number of reasons, including their flexibility and ability to handle predictors of mixed types (i.e., qualitative as well as quantitative). We have now seen four approaches for fitting an ensemble of trees: bagging, random forests, boosting, and BART.
New packages used today are:
After Reading Week, we will do the final two topics from ISLR2: Support Vector Machines and Deep Learning. The latter will be a very high-level overview of a topic that could be an entire course (and often is multiple courses, see, e.g., some of the COIS offerings at Trent).
The material of this week is Chapters 8.1-8.2 of ISLR2, discussing tree-based methods.
Readings for the two weeks following reading week are Chapters 9.1-9.5 for week 8, and 10.1-10.7 for the following, week 9.
