Sub topic 1
Decision trees as weak learners
Gradient boosting builds its model out of many small decision trees. This chapter covers how one tree is built, why a deliberately shallow tree is the right building block, and which properties of trees the later chapters depend on.
Prerequisites
This chapter assumes you can:
- Read and write Python and NumPy code.
- Explain features, labels and a train/validation split.
- Describe a decision tree as a set of yes/no questions about features.
- Recognize overfitting and read metrics such as mean squared error (MSE).
You do not need to know boosting yet. The next chapter introduces it.
What a tree computes
A decision tree splits the feature space into rectangular regions. Each region has one constant prediction. In regression, the constant is the mean of the training targets in that region. In classification, it is the majority class or the class proportions.
Every internal node asks a question of the form feature_j <= threshold. A sample goes left if the answer is yes and right otherwise. It keeps going until it reaches a leaf, and the leaf's value is the prediction.
The prediction function is piecewise constant. It has steps and no slope. Two consequences follow:
- A tree cannot extrapolate. Beyond the range of the training data, it predicts the value of the nearest edge region.
- A tree represents interactions without extra work. The second question depends on the answer to the first, so effects can differ by region.
How a tree is grown
Training uses greedy, top-down recursive splitting. At each node the algorithm does the following:
- For every feature, consider candidate thresholds. These are midpoints between consecutive sorted unique values.
- Score each split by how much it reduces an impurity measure.
- Pick the best (feature, threshold) pair, partition the samples, and repeat on each child.
For regression the impurity is usually the sum of squared errors (SSE) around the node mean. For classification it is typically Gini impurity or entropy. A split's quality is the parent's impurity minus the combined impurity of the two children.
The search is greedy. Each split is optimal for the current node, with no look-ahead. A split that looks weak alone but enables a strong second split can be missed. Finding the globally optimal tree is NP-hard, so every practical library grows trees greedily.
The function below implements the one-feature version of this search. It scans every midpoint and returns the split with the lowest total SSE. It is compared against scikit-learn's depth-1 tree, called a stump.
import numpy as np
from sklearn.tree import DecisionTreeRegressor
def best_split(x, y):
order = np.argsort(x)
x, y = x[order], y[order]
best_threshold, best_sse = None, np.inf
for i in range(1, len(x)):
if x[i] == x[i - 1]:
continue # no threshold separates equal values
left, right = y[:i], y[i:]
sse = ((left - left.mean()) ** 2).sum() + ((right - right.mean()) ** 2).sum()
if sse < best_sse:
best_threshold, best_sse = (x[i - 1] + x[i]) / 2, sse
return best_threshold, best_sse
rng = np.random.default_rng(0)
x = rng.uniform(-3, 3, size=200)
y = np.sin(x) + rng.normal(0, 0.3, size=200)
threshold, sse = best_split(x, y)
stump = DecisionTreeRegressor(max_depth=1).fit(x.reshape(-1, 1), y)
print("manual threshold:", round(threshold, 4), "SSE:", round(sse, 3))
print("sklearn threshold:", round(float(stump.tree_.threshold[0]), 4))Both thresholds should match. This loop sorts once per feature and tests every position, which is why exact split finding gets expensive on large data. A later chapter covers the histogram method XGBoost uses to avoid this cost.
Depth controls bias and variance
A tree can keep splitting until every leaf holds a single sample. That tree reproduces the training data exactly and fits the noise along with the signal. A tree with few splits is too coarse to capture the pattern. This is the usual tradeoff:
| Tree size | Bias | Variance | Typical behavior |
|---|---|---|---|
| Very shallow (depth 1 to 2) | High | Low | Underfits, but stable across resamples |
| Moderate (depth 3 to 6) | Medium | Medium | Captures main structure and some interactions |
| Fully grown | Low | High | Memorizes noise, unstable |
The experiment below makes this visible. The target is a noisy sine wave, and the only thing that changes is max_depth.
import numpy as np
from sklearn.metrics import mean_squared_error
from sklearn.model_selection import train_test_split
from sklearn.tree import DecisionTreeRegressor
rng = np.random.default_rng(0)
X = rng.uniform(-3, 3, size=(600, 1))
y = np.sin(X[:, 0]) + rng.normal(0, 0.3, size=600)
X_train, X_val, y_train, y_val = train_test_split(
X, y, test_size=0.3, random_state=0
)
for depth in [1, 2, 3, 5, 10, None]:
tree = DecisionTreeRegressor(max_depth=depth, random_state=0)
tree.fit(X_train, y_train)
train_mse = mean_squared_error(y_train, tree.predict(X_train))
val_mse = mean_squared_error(y_val, tree.predict(X_val))
print(f"depth={str(depth):>4} train MSE={train_mse:.3f} val MSE={val_mse:.3f}")Expect training error to fall steadily as depth grows, reaching zero for max_depth=None. Validation error falls at first, then flattens or rises. The noise has variance 0.09, so no model can reliably beat a validation MSE near that value.
Why shallow trees make good weak learners
A weak learner is a model only slightly better than a trivial baseline. Boosting does not need strong base models. It needs ones that are cheap, stable and better than nothing, and shallow trees fit that description:
- Low variance. A depth-3 tree changes little when the training set is resampled. The ensemble can then reduce bias without inheriting a large variance from each member.
- Cheap to fit. Cost grows with the number of nodes, and a depth-d tree has at most 2^d leaves. Hundreds of rounds stay affordable.
- Handle mixed data. Trees are invariant to monotonic transformations of a feature, so no scaling is needed. They accept numeric features of any range and, in XGBoost, missing values.
- Capture interactions. A tree of depth d can model interactions among up to d features. This is why
max_depthis the main control over interaction order in boosted models.
The contrast with bagging models such as random forests is worth noting. Random forests average many deep, high-variance trees to cut variance. Boosting combines many shallow, high-bias trees to cut bias. The next chapter develops this difference.
Common errors and edge cases
- Expecting extrapolation. A tree trained on x in [0, 10] predicts a constant for x = 50. Time trends and other growing quantities need a feature that removes the trend, or a model that handles it.
- Judging a tree by training error. A fully grown tree scores perfectly on training data. Always compare against a held-out set.
- Treating feature importance from one deep tree as reliable. A small data change can alter the top split and reshuffle everything below it.
- Assuming scaling matters. It does not for trees. Standardizing features wastes effort but does no harm.
- Ignoring ties. If many samples share a feature value, no threshold can separate them. Low-cardinality features give few candidate splits.
- Leaf values on tiny nodes. A leaf holding one or two samples gives a noisy mean. Minimum sample or weight limits per leaf guard against this. XGBoost's version of that control is
min_child_weight, covered later.
Do not read a large gap between training and validation error as a reason to switch model families. For a single tree, it usually means the tree is too deep. Reduce `max_depth` or set a minimum leaf size first.What carries forward
Three facts from this chapter matter for the rest of the tutorial:
- A tree is a piecewise-constant function whose leaf values can be set independently of its structure.
- Tree depth sets the bias, the variance and the interaction order.
- Greedy split search is the main computational cost, and XGBoost's tree methods are about doing it faster.
Exercise
You fit DecisionTreeRegressor(max_depth=None) on a noisy dataset and get training MSE of 0.000 and validation MSE much higher than the noise variance. Which of bias or variance is the problem, and what is one change that helps?
Show answer
Variance is the problem. The tree has memorized noise in the training set. Limiting the depth (for example max_depth=4) or requiring a larger minimum leaf size reduces variance and usually lowers validation error.
Exercise
A tree is trained on a feature with values between 0 and 100. At prediction time, a sample has the value 250. What does the tree predict, and why?
Show answer
It predicts the value of the leaf covering the highest region of the training data. Every split threshold is below 250, so the sample follows the "greater than" branches to the rightmost leaf. Trees do not extrapolate trends.
Exercise
Why does a sum of depth-1 trees (stumps) never model an interaction between two features?
Show answer
Each stump splits on one feature only, so its output depends on a single feature. A sum of such functions is additive in the features. An interaction needs a later split to depend on the outcome of an earlier split, which requires depth 2 or more.