Trees and ensembles
From rules to learned trees
A decision tree predicts by asking a sequence of questions about features. Internal nodes contain tests, branches represent outcomes, and leaves supply predictions. A classifier leaf may predict the majority label among training samples reaching it; a regression leaf may predict a numerical average. A fitted tree learns its questions from training data. A hand-written tree is a rule system, not proof that learning occurred. Use a fictional warehouse: 1 means review replenishment and 0 means no review. Stock and forecast demand are nonnegative whole-unit counts. The next example is a deliberately fixed policy, not trained.
Trace a two-split tree
At the root, stock at or below 3 leads directly to review. Otherwise, demand above 8 leads to review; all other cases return 0. Trace (3, 2), (4, 8), (4, 9). The outputs are 1, 0, 1. Equality belongs to the low-stock branch at 3 and the low-demand branch at 8. The function assumes valid finite integer counts. It does not validate business inputs or actually order goods.
def stock_tree(stock, demand): if stock <= 3: return 1 if demand > 8: return 1 return 0
for stock, demand in [(3, 2), (4, 8), (4, 9)]: print(stock_tree(stock, demand))How a split is learned
A classification tree can choose a split that reduces impurity, a measure of label mixing. Gini impurity is 1 minus the sum of squared class proportions. For four training examples with labels [0,0,1,1], parent impurity is 0.5. A split yielding [0,0] and [1,1] has weighted child impurity 0 and gain 0.5. A split yielding [0] and [0,1,1] has weighted impurity (1/4)0+(3/4)(4/9)=1/3, so gain is 1/6. Compare weighted, not unweighted, child scores. This only compares candidate splits on training data; neither guarantees test accuracy. A regression tree instead uses a numerical loss or impurity criterion such as squared error.
Depth and generalization
A deep tree may memorize training noise, leaving very few samples per leaf. Maximum depth, minimum leaf size and pruning limit complexity; choose them on validation data. A shallow tree may underfit interactions. Axis-aligned numeric splits are largely insensitive to monotonic changes of feature units when the corresponding split thresholds are transformed, unlike Euclidean distance. Missing data and categorical input depend on the implementation. A traceable path explains the decision rule, not a causal relationship.
Voting, bagging and random forests
An ensemble combines predictions. Three fixed classifiers voting [1,0,1] yield label 1 by majority. Our hard-vote helper resolves even ties to 0; this is a local policy, not a universal library rule. A soft vote averages class probabilities, with compatible class ordering, before choosing a label. Bagging trains estimators on resampled training data and aggregates them. A typical random forest also samples candidate features at splits, encouraging diversity; averaging can reduce variance when errors differ. Some implementations aggregate probabilities instead of hard labels. Three handwritten votes are not a trained forest. The helper expects a nonempty binary list.
def majority_vote(votes): if not votes or any(v not in (0, 1) for v in votes): raise ValueError("Nonempty binary votes required") return int(sum(votes) * 2 > len(votes))
print(majority_vote([1, 0, 1]))print(majority_vote([0, 1]))Boosting is not independent voting
Boosting adds learners sequentially to improve an existing ensemble. For squared-error gradient boosting, a simple initial prediction of 4 on targets [3,5,7] leaves residuals [-1,1,3]. Suppose a next weak learner predicts [-1,1,1]; with learning rate 0.5 the new predictions are [3.5,4.5,4.5]. The update is illustrative, not a fitted tree. Classification boosting uses an appropriate loss and can combine scores instead of labels. AdaBoost adjusts emphasis on hard examples; gradient boosting follows loss gradients. Noise, excessive depth and too many rounds can hurt generalization. Random forests and boosting have different cost and tuning trade-offs; neither always wins.
Practice and decision checklist
Predict the fixed tree at stock=3,demand=100 and stock=9,demand=8; answers are 1 and 0. For votes [1,1,0,0], our tie policy returns 0. Compare a shallow tree, forest and boosted model on the same train/validation split and metric, not by training accuracy. Record fitting time, prediction latency, memory, class-specific errors and interpretability needs; lock settings before test evaluation. The next lesson compares distance, probability and margin approaches. More detailed training algorithms belong to the ML track.
Check Your Understanding
Solidify your learning with the interactive assessment directly below this lesson.
Concept Quiz & Questions
Trees and ensembles quiz
Apply model-family concepts to small original examples.
For stock = 3 and demand = 2, which path does the fixed stock_tree take?
What is Gini impurity for [0,0,1,1]?
What does the hard-vote helper return for [1,0]?
Which description best matches a typical random forest classifier?
How does gradient boosting typically build its ensemble?