A classification tree splits the predictor space in two, then splits each part in two, and so on. Each split tests one predictor against one threshold, so every leaf is a rectangle. A new point follows the tests from the root to a leaf and gets that leaf's majority class.
With \(\hat p_k\) the share of a node's points in class \(k\):
Both are 0 for a node of one class and largest for an even mix: \(G = 0.5\) and \(H = \ln 2 = 0.693\) with two classes. The two measures usually lead to the same splits.
For a node with \(n\) points, a split sends \(n_L\) left and \(n_R\) right. rpart chooses the predictor and threshold that minimize \(n_L G_L + n_R G_R\), which is the same as maximizing the drop
It tries every threshold halfway between neighboring values of each predictor, keeping at least the minimum leaf size on each side. The search is greedy: each split is the best one for its node alone, with no look ahead to later splits.
rpart splits a node only if it contains at least minsplit points (here twice the minimum leaf size), and keeps a split only if the subtree below it lowers the training error by at least cp, the complexity parameter, as a share of the root's error. With cp = 0, any decrease counts. A split can lower the Gini impurity without changing any leaf's majority class; rpart drops such a split unless the splits beneath it lower the error.
rpart grows the tree depth first. Each node's split depends only on that node's points, so the finished tree is the same in any order. Each click of Split adds the split that lowers the total impurity, \(\sum n_t G_t\), the most.
The call rpart(y ~ x1 + x2, data, method = "class", parms = list(split = "gini"), control = rpart.control(minsplit = 10, minbucket = 5, cp = 0, xval = 0)) grows this tree, and part 1 of The Script runs it on these data.
Training error can only fall as a tree gains splits, because each split lowers the error on the points it was chosen for. Test error measures prediction on new points. It falls while the splits capture the true function and rises once they fit the noise. The expected test MSE of a prediction splits into three parts:
A shallow tree has large bias and small variance; a deep tree has the reverse. \(\sigma^2\) is the noise variance, \(0.5^2 = 0.25\) here, and no model can predict new points with a lower expected MSE.
With a minimum leaf size of 5, the tree runs out of splits at some depth (11 on the default data). Deeper limits change nothing after that.
For a tree \(T\) with \(|T|\) leaves and sum of squared errors \(\text{SSE}(T)\), rpart charges \(\alpha\) per leaf:
For each \(\alpha\), one subtree of the full tree minimizes \(R_\alpha\), and as \(\alpha\) grows these subtrees are nested: each one is the previous with its weakest splits removed. rpart reports \(\text{cp} = \alpha / \text{SSE}(\text{root})\); the cp table lists the sequence, and prune(fit, cp) returns one member of it.
With xval = 10, rpart cross-validates every member of the sequence: printcp() adds the column xerror, and plotcp() draws it. The usual choice is the smallest tree whose xerror is within one standard error of the lowest. The curves here use the 500 test points instead, so they show the test error exactly.
Part 2 of The Script fits one tree for each maxdepth in rpart.control(), then prints the pruning sequence with printcp(full) and prunes with prune(full, cp = full$cptable[k, "CP"]).
Bagging draws \(B\) bootstrap samples, each of \(n\) points drawn with replacement from the \(n\) training points, grows a tree on each, and averages the trees' predictions. For classification, the trees vote.
Each of the \(n\) draws misses a given point with probability \(1 - 1/n\), so
If each tree's prediction at \(x\) has variance \(\sigma^2\) and two trees' predictions have correlation \(\rho\), the average of \(B\) trees has variance
More trees shrink the second term toward 0, so the error levels off and more trees never overfit. The first term stays: trees grown on overlapping samples of the same data are correlated. Random forests lower \(\rho\).
Point \(i\) is out-of-bag for the trees whose samples did not draw it. Its OOB prediction \(\hat y_i^{\text{OOB}}\) averages those trees only, and the OOB MSE is \(\frac1n\sum (y_i - \hat y_i^{\text{OOB}})^2\) over the points that have been out-of-bag at least once. The OOB MSE and the test MSE score different points, so they differ by chance; on the default data, 100 trees give 0.2859 and 0.2900.
The loop in part 3 of The Script draws each sample with sample(n, replace = TRUE) and fits rpart() to it. The call randomForest(y ~ ., mtry = p) bags fully grown trees in one step, and The Anvil uses it.
For each of \(B\) trees: draw a bootstrap sample; grow a tree on it, and at every split draw mtry of the \(p\) predictors at random and choose the best split among those only; stop splitting a node once it contains no more than the minimum node size, with no pruning. Average the trees' predictions (vote for classification). With mtry \(= p\) this is bagging.
\(\rho\) is the correlation between two trees' predictions and \(\sigma^2\) the variance of one. When one predictor is strong, bagged trees all split on it first and \(\rho\) is high. With a random subset, many splits cannot choose that predictor, so the trees differ more and \(\rho\) falls, but each tree is a little less accurate. The best mtry balances the two, and OOB error estimates where that is.
randomForest uses mtry \(= \max(1, \lfloor p/3 \rfloor)\) for regression and \(\lfloor \sqrt p \rfloor\) for classification, 500 trees, and a minimum node size of 5 for regression and 1 for classification. tuneRF() searches mtry by OOB error. The minimum node size is randomForest's nodesize: a node with that many points or fewer is not split. rpart's minimum leaf size (minbucket) is a different rule: every leaf must keep at least that many points.
For each tree and predictor \(j\), randomForest shuffles \(x_j\) among the tree's out-of-bag points and records how much the tree's OOB MSE rises, \(d_{bj}\). randomForest calls the result %IncMSE, for increase in mean squared error:
It is a ratio to a standard error, so it has no units, and values near 0 are consistent with a predictor the trees do not use. importance(rf, type = 2) gives the other measure, the total drop in SSE from splits on each predictor.
Every forest on this tab starts from set.seed(2026), so a forest's first 200 trees are the same whether it grows 200 or 300. At the default settings, the comparison's forest at mtry = 3 is the first 200 trees of the 300-tree forest in step 2.
Part 4 of The Script grows this forest with randomForest(y ~ ., data, mtry = 3, ntree = 300, importance = TRUE). In the result, rf$mse is the OOB MSE after each tree, and importance(rf, type = 1) returns %IncMSE.
Tree: one rpart tree with the max depth you set and a minimum leaf size of 5. Bagging: randomForest() with mtry \(= p\), so every split may choose from every predictor. Its trees stop splitting a node only once it contains 5 or fewer points, so they grow far deeper than the Bagging tab's depth-6 trees. Forest: the same with the mtry you set.
Choosing the depth by test MSE and then reporting that same test MSE makes the tree look a little better than it will on new data, because the choice used the test points. The mtry sweep selects by OOB MSE, which uses only the training points.
The data come from set.seed(376), and every ensemble from set.seed(2026). The sweep of the number of trees grows one 500-tree forest and reads its test MSE after each size: with one seed, the first 100 trees of that forest are the 100-tree forest.
Part 5 of The Script fits rpart() in a loop over maxdepth, then randomForest(y ~ ., mtry = 10) for bagging and randomForest(y ~ ., mtry = 3) for the forest.
| Call | What it returns |
|---|---|
rpart(y ~ ., data, method = "class") | A tree. method = "anova" (the default for a numeric y) grows a regression tree. |
rpart.control(maxdepth, minsplit, minbucket, cp, xval) | The stopping rules: the depth limit, the smallest node rpart will split, the minimum leaf size, the complexity a split must add, and the number of cross-validation folds. |
printcp(fit), plotcp(fit) | The pruning sequence: each row's CP, its number of splits, and its training error relative to the root (with xval > 0, also the cross-validated error). |
prune(fit, cp) | The member of the pruning sequence for that cp. |
predict(fit, newdata, type = "class") | Predicted classes; with no type, class probabilities for a classification tree and means for a regression tree. |
randomForest(y ~ ., data, mtry, ntree, nodesize, importance = TRUE) | A forest. mtry is the number of predictors each split may choose from; mtry = p is bagging. |
rf$mse | The OOB MSE after each tree. |
importance(rf, type = 1) | %IncMSE: the rise in OOB MSE when a predictor is shuffled, divided by its standard error. |
predict(rf, newdata, predict.all = TRUE) | The forest's prediction and, in $individual, each tree's. |