By the end of this lecture, you should be able to:
describe a tree as a partition of predictor space into rectangular regions;
calculate a regression split using residual sum of squares;
calculate a classification split using Gini impurity;
explain what greedy recursive binary splitting gains and gives up;
state the prediction made by a regression or classification leaf;
interpret the cost-complexity pruning objective; and
apply fixed-fold cross-validation and the one-standard-error rule without using test rows.
Why use a tree?
Linear models use one set of coefficients across the predictor space. A tree begins with a different question.
Guiding question. Can one simple yes-or-no question divide the current observations into two groups that are easier to predict?
The process repeats inside each resulting group. A final prediction can therefore include interactions automatically. For example, a rule may ask about only when has already crossed a threshold.
The shared classification example has two predictors drawn independently and uniformly from and a binary response. The probability of class 1 is when and , and when and . It is elsewhere. No single split can isolate both high-probability regions.
Both languages use the supplied classification data and regression data. Save them in data/decision-trees/ and run the blocks in your chosen language from the folder containing data/. The classification file already records the training/test split and the five training-fold assignments.
A binary classification sample whose population rule needs several splits.
Noise keeps the classes from separating perfectly. The goal is not to draw a box around every unusual point. The goal is to find a partition that predicts well on future observations.
A tree is a piecewise-constant rule
Each internal node asks a question of the form
Observations satisfying the question go left; the rest go right. After several questions, the predictor space is divided into terminal regions , called leaves. Here, denotes the number of training observations in region .
For regression, the prediction in leaf is its training-response average:
For classification, the estimated probability of class is its training proportion in the leaf:
The usual class prediction is the class with the largest . Thus, even a classification tree contains more information than its final hard label.
Regression trees choose splits by RSS
Suppose a node contains index set . A candidate split creates
For fixed child nodes, the constants minimizing squared error are the child sample means. Therefore the best split minimizes
Equivalently, it maximizes the reduction from the parent RSS. The next calculation checks every midpoint between consecutive observed values while requiring at least 20 observations in each child.
The first split is near the true change in the mean at . It is not exactly because the algorithm sees a finite noisy sample, not the population rule.
Local decision, global consequence. The algorithm chooses the split with the best immediate loss reduction inside the current node. That split changes which later splits are possible, but the algorithm does not revisit it after seeing the future tree.
Classification trees need an impurity measure
For a node with class proportions , common impurity measures are
All are zero for a pure node. Gini and entropy respond more smoothly to changing class proportions than misclassification impurity, so they are commonly used to grow a tree.
For a candidate split, the weighted child Gini is
The chosen split gives the largest decrease from the parent Gini.
# Search root splits and choose the largest decrease in Gini impurity.def gini_py(y): counts = np.array([(y == label).sum() for label in [0, 1]]) proportions = counts / counts.sum()return1.0- np.sum(proportions**2)parent_gini_py = gini_py(tree_train_py["y"].to_numpy())best_classification_split_py =Nonefor feature in ["x1", "x2"]: values = tree_train_py[feature].to_numpy() ordered = np.sort(np.unique(values)) thresholds = (ordered[1:] + ordered[:-1]) /2.0for threshold in thresholds: left = values <= thresholdif left.sum() <20or (~left).sum() <20:continue left_gini = gini_py(tree_train_py.loc[left, "y"].to_numpy()) right_gini = gini_py(tree_train_py.loc[~left, "y"].to_numpy()) weighted_gini = ( left.sum() * left_gini + (~left).sum() * right_gini ) /len(values) gain = parent_gini_py - weighted_gini candidate = {"feature": feature,"threshold": threshold,"parent_gini": parent_gini_py,"left_n": int(left.sum()),"left_gini": left_gini,"right_n": int((~left).sum()),"right_gini": right_gini,"gain": gain, }if ( best_classification_split_py isNoneor gain > best_classification_split_py["gain"] +1e-12 ): best_classification_split_py = candidatepd.DataFrame([best_classification_split_py])
feature threshold parent_gini ... right_n right_gini gain
0 x1 0.352782 0.491288 ... 157 0.480506 0.024841
[1 rows x 8 columns]
The first Gini reduction is modest. That is expected: one axis-aligned cut cannot isolate both high-probability regions. Later splits can refine each child separately.
Recursive binary splitting is greedy
After choosing the root split, the algorithm repeats the search within each child. It does not go back and replace the root because a later combination of splits would be better.
This greedy strategy makes tree fitting practical and easy to explain. It does not guarantee the globally best tree of a given size. Finding that global tree would require comparing an enormous number of possible split sequences.
NoteWhy grow first and prune later?
An early stopping rule must decide whether a split looks useful before seeing what later splits could do. A split with a small immediate gain may open the way to useful descendants. The common CART strategy therefore grows a fairly large tree and then compares nested subtrees by pruning.
Cost-complexity pruning
A split and a whole tree answer different questions. The pair describes one locally chosen split inside the current node. The symbol describes an entire tree. Split impurity chooses a local branch using training data; cross-validation chooses among whole candidate trees by estimated prediction error.
Let be a grown tree and let be a subtree. Write for its number of leaves. Here, is the loss on the training observations. Cost-complexity pruning chooses, for each ,
For regression, is usually the leaf RSS. For classification, it can be the leaf misclassification count or another stated loss. Larger applies a larger penalty to each additional leaf and therefore favors a smaller tree.
The weakest-link algorithm creates a nested sequence:
At each step, it removes the branch whose removal produces the smallest increase in training loss per leaf removed. This is much more efficient than comparing every possible subtree.
Training loss cannot choose the tree size
The large tree was built to fit the training sample. Its training loss is optimistic. We therefore use the supplied five folds to compare pruning settings on the 500 training observations. We keep the 1,000 test observations for the final evaluation.
The manual calculations above show how one split is chosen. We now let standard packages repeat that calculation through a tree: rpart in R and DecisionTreeClassifier in Python. Both use Gini splits, at least 20 observations per leaf, and a maximum depth of six. Only x1 and x2 are predictors; the file’s true probabilities and fold labels are not predictors.
The packages differ in how they prune. With the default class costs used here, rpart uses misclassification loss, and its cp measures complexity relative to the unsplit tree’s loss. Scikit-learn uses the sum of leaf Gini impurities weighted by their fractions of training observations; ccp_alpha is the penalty on that scale. Thus the same numerical penalty need not give the same tree. We use a fixed grid for each package and compare both by validation misclassification error. These conventions are described in the rpart introduction and scikit-learn pruning documentation.
Each fold’s tree must be grown using only the other four folds. Pruning a tree grown once on all 500 observations would let the validation labels influence its splits.
Grow one tree per fold, then prune it at each candidate cp. Setting xval = 0 disables the package’s internal cross-validation because we supply the folds explicitly.
Average the fold errors. The minimum-error rule chooses the first minimum on this increasing grid. The one-standard-error rule chooses the largest eligible cp, which favors a smaller tree.
rule cp leaves cv_error test_error
1 Minimum CV 0.00 5 0.2099546 0.221
2 One standard error 0.12 5 0.2099546 0.221
Five-fold classification error for the rpart complexity grid. The horizontal line is the one-standard-error threshold.
For each fold and penalty, the fitting call grows a tree on that fold’s training observations and prunes it. The random seed fixes how the package handles tied split choices.
In a Jupyter environment, please rerun this cell to show the HTML representation or trust the notebook. On GitHub, the HTML representation is unable to render, please try loading this page with nbviewer.org.
Average the fold errors. The minimum-error rule chooses the first minimum on this increasing grid. The one-standard-error rule chooses the largest eligible ccp_alpha, which favors a smaller tree.
rule ccp_alpha leaves cv_error test_error
Minimum CV 0.00 19 0.209955 0.221
One standard error 0.04 5 0.209955 0.221
Five-fold classification error for the scikit-learn complexity grid. The horizontal line is the one-standard-error threshold.
For these grids, both language routes have a minimum mean validation error of about . Several penalty values give that same error, and the minimum-error rule takes the first one. In R, both selected settings give a five-leaf tree. In Python, the minimum-error setting gives 19 leaves, while the one-standard-error setting gives five. The extra Python leaves refine class proportions without changing the class predictions on these test observations. All four selected fits have test error .
The one-standard-error rule is not guaranteed to choose a smaller tree. It did so in Python, but the two R settings produce the same tree. The curves also show why stronger pruning is not always better: after enough branches are removed, the validation error rises substantially. These results describe this sample and these candidate grids; they do not establish that either package is generally more accurate.
WarningInterpreting the fold-based standard error
As in ridge and lasso, the rule uses the conventional fold-based standard-error estimate at the minimizing candidate:
Here, are its validation-fold errors and is the number of folds, which is five in this example. The standard deviation describes variation among fold errors. Dividing by gives the conventional summary used by the tuning rule. The fold errors are dependent because their training samples overlap, so this allowance is a heuristic, not a confidence interval for prediction error.
What the selected partition looks like
Use each language’s one-standard-error tree to predict a fresh grid of locations. The grid has no observed outcomes and is only for displaying the fitted boundary. We calculate the Bayes regions directly from the population rule stated at the start of the lecture.
The one-standard-error tree’s class boundary and the population Bayes boundary.
The fitted rule finds the two high-probability regions, but its thresholds differ from the population thresholds because it was learned from a noisy sample. Both boundaries in this example have horizontal and vertical segments. A smooth or tilted population boundary would require more tree splits to approximate. This figure explains the fitted decisions; the separate test error evaluates them.
Categorical predictors require an explicit representation
For a numeric predictor, a split has the form . For an unordered categorical predictor, the analogous question is whether its level belongs to some set :
Tree software does not handle this situation in one universal way. A native factor implementation may compare groups of levels directly or use an ordering shortcut. A one-hot representation instead creates several binary indicators. These representations can lead to different candidate splits and different trees.
Keep three practical points in mind:
decide how categorical predictors will be represented before tuning;
learn levels and any encoding from the training observations inside each fold; and
define what happens when a validation or test row contains a level not seen during fitting.
The representation also affects importance summaries. If one original predictor becomes several indicators, inspect both indicator-level results and a sensible grouped summary before drawing conclusions.
Keep the data roles separate
Tree analyses are especially vulnerable to accidental reuse of information because they involve many choices: missing-value handling, class weights, depth, minimum leaf size, impurity, pruning, and sometimes probability thresholds.
Use the following order:
set aside the test rows;
fix the cross-validation folds on the training rows;
inside each fold, learn every preprocessing step and grow the candidate tree from that fold’s training observations;
evaluate the entire candidate path on the validation rows;
choose a complexity rule using only validation results;
refit the chosen procedure on all training rows; and
evaluate once on the untouched test rows.
For example, if missing predictor values are replaced by column means, estimate those means from the training observations within each fold and reuse them for its validation observations.
Check your understanding
Why does a regression leaf predict with its training-response average?
Why can Gini impurity distinguish two candidate splits that have the same misclassification error?
What does the greedy algorithm give up when it commits to the best current split?
Why can training loss guide a split but not select the final tree size?
What does increasing do in the cost-complexity objective?
Why can native categorical splits and one-hot encoding produce different trees?
Key ideas
A tree predicts with piecewise-constant leaf values.
Recursive binary splitting is greedy, so it is efficient but not globally optimal.
Leaf probabilities are often more informative than hard class labels.
Cost-complexity pruning compares fit against the number of leaves.
The one-standard-error rule chooses the simplest candidate within a conventional fold-based error allowance. It does not always differ from the minimum-error choice.
Folds, preprocessing, pruning, and test evaluation must have separate roles.
References and further reading
Breiman, L., Friedman, J. H., Olshen, R. A., and Stone, C. J. (1984). Classification and Regression Trees. Wadsworth.