Sub topic 11
A stronger model: histogram gradient boosting
This chapter assumes you have the train/test split, the mean-prediction baseline, and the Ridge pipeline with 5-fold cross-validation from the earlier chapters. It also assumes you know what a decision tree is: a model that splits the data with a series of yes/no questions about feature values. Here you add a second model, compare it with Ridge under the same cross-validation setup, and learn where it can go wrong.
Why try a different model family
Ridge regression fits one weighted sum of the features. That is a poor fit for housing data. The effect of MedInc (median income) depends on location, and location is a nonlinear function of Latitude and Longitude. A linear model can only approximate that with a flat plane.
Gradient boosting builds many small decision trees, one after another. Each tree tries to correct the mistakes of the trees before it. The sum of all the trees can follow curves, thresholds, and interactions between features without you designing them.
The working model
Boosting for regression with squared error works like this:
- Start with a constant prediction, the mean of the training target. This is the same thing the baseline does.
- Compute the residuals, which are the true value minus the current prediction, for every training row.
- Fit a small tree to predict those residuals from the features.
- Add the tree's output to the running prediction, multiplied by the
learning_rate, a number between 0 and 1 that shrinks each tree's contribution. - Repeat steps 2 to 4 for
max_iterrounds.
Small steps matter. A learning rate of 0.1 means each tree fixes only a tenth of the remaining error it sees. This makes the final model less likely to fit noise. For losses other than squared error, the tree fits the negative gradient of the loss instead of plain residuals. That is where the name comes from.
What "histogram" means
Finding the best split for a numeric feature normally means testing a threshold between every pair of sorted values. With 16,000 rows and 8 features, repeated for hundreds of trees, that is slow.
HistGradientBoostingRegressor first sorts each feature's values into at most 255 bins (the max_bins parameter). Splits are then tested only between bins, and the algorithm sums gradients per bin instead of per row. This makes training much faster on large datasets, at the cost of slightly coarser thresholds. It is the same idea used by LightGBM, and scikit-learn's implementation is modeled on it.
Three practical consequences follow:
- No scaling is needed. Trees compare a feature to a threshold. Multiplying a feature by 1,000 or applying any increasing transform gives the same splits, so
StandardScaleradds nothing here. - Missing values are handled. NaN is allowed in the input, and each split learns which side missing values should go to. The California data has no missing values, so this does not matter in this project.
- Categorical columns have native support. You pass
categorical_features. This dataset has none.
Scoring it with the same cross-validation
To compare models fairly, use the same training data, the same number of folds, and the same metric as for Ridge.
from sklearn.datasets import fetch_california_housing
from sklearn.ensemble import HistGradientBoostingRegressor
from sklearn.model_selection import cross_val_score, train_test_split
housing = fetch_california_housing(as_frame=True)
df = housing.frame
X = df.drop(columns="MedHouseVal")
y = df["MedHouseVal"]
X_train, X_test, y_train, y_test = train_test_split(
X, y, test_size=0.2, random_state=42
)
hgb = HistGradientBoostingRegressor(random_state=42)
scores = cross_val_score(
hgb, X_train, y_train, cv=5, scoring="neg_mean_absolute_error"
)
print("HistGradientBoosting CV MAE:", -scores.mean())Two details from earlier chapters carry over. First, the split is identical because random_state=42 is the same. Second, scikit-learn scorers follow the rule "higher is better", so MAE is returned as a negative number and you flip the sign when you print it.
On this data you should see a cross-validated MAE near 0.3, in units of $100,000. That is about $30,000. The mean baseline is around 0.9 and Ridge around 0.5. Exact digits can differ slightly between scikit-learn versions, so compare your own numbers with each other and not with mine.
There is no make_pipeline here, and that is fine. The model has no preprocessing step that learns from data, so there is nothing that can leak between folds. If you later add an imputer or encoder, put it in a pipeline as you did for Ridge.
| Property | Ridge in a pipeline | HistGradientBoostingRegressor |
|---|---|---|
| Shape of fit | One linear function | Sum of many trees, can be nonlinear |
| Needs scaling | Yes | No |
| Handles NaN | No | Yes |
| Interpretability | Read coefficients | Needs tools like permutation importance |
| Main risk | Underfitting | Overfitting |
| Typical fit time here | Under a second | A few seconds |
Checking for overfitting
A single CV number does not show how well the model fits the data it trains on. cross_validate can also report the training score and the fit time for each fold.
from sklearn.datasets import fetch_california_housing
from sklearn.ensemble import HistGradientBoostingRegressor
from sklearn.model_selection import cross_validate, train_test_split
housing = fetch_california_housing(as_frame=True)
df = housing.frame
X = df.drop(columns="MedHouseVal")
y = df["MedHouseVal"]
X_train, X_test, y_train, y_test = train_test_split(
X, y, test_size=0.2, random_state=42
)
result = cross_validate(
HistGradientBoostingRegressor(random_state=42),
X_train,
y_train,
cv=5,
scoring="neg_mean_absolute_error",
return_train_score=True,
)
print("Train MAE:", -result["train_score"].mean())
print("Validation MAE:", -result["test_score"].mean())
print("Mean fit time (s):", result["fit_time"].mean())Expect a train MAE lower than the validation MAE. A small gap is normal. A large gap, such as train 0.05 against validation 0.35, means the model memorizes training rows, and you should reduce its capacity (fewer leaves, a lower learning rate, or fewer iterations). A gap in the other direction, with both scores bad, means underfitting.
Early stopping and the number of trees
The default max_iter=100 sets the maximum number of trees. Early stopping can end training sooner. By default (early_stopping="auto") it turns on when the training set has more than 10,000 rows. Our training split has 16,512 rows, so it is on.
Here is how it works. The model holds out 10% of the rows it was given (validation_fraction=0.1), checks the loss on them after each tree, and stops if there is no improvement for 10 rounds (n_iter_no_change=10). You can see how many trees were actually built in n_iter_.
from sklearn.datasets import fetch_california_housing
from sklearn.ensemble import HistGradientBoostingRegressor
from sklearn.model_selection import train_test_split
housing = fetch_california_housing(as_frame=True)
df = housing.frame
X = df.drop(columns="MedHouseVal")
y = df["MedHouseVal"]
X_train, X_test, y_train, y_test = train_test_split(
X, y, test_size=0.2, random_state=42
)
model = HistGradientBoostingRegressor(random_state=42).fit(X_train, y_train)
print("Early stopping active:", model.n_iter_ < model.max_iter)
print("Trees built:", model.n_iter_)The internal validation rows come from whatever data fit receives. Inside cross_val_score, that is the training part of each fold. The CV validation fold stays untouched, so scores remain honest. The random_state=42 argument also fixes which rows are held out internally, so repeated runs give the same result.
Common errors
- Scaling "just in case." It does no harm to the score, but it adds code and a pipeline step that does nothing. Leave it out.
- Comparing scores from different setups. If Ridge used
cv=5on the training set and boosting usescv=3on the full data, the numbers cannot be compared. Keep the data, folds, and metric identical. - Forgetting the sign. Printing
scores.mean()gives a negative MAE. A model with "-0.31" is not worse than one with "-0.53"; it is better. - Evaluating on the test set while choosing. The test set is for the final chapter. Compare Ridge and boosting only with CV on the training data.
- Reading
n_iter_as a setting. It is a result of fitting, not a parameter. To change the number of trees, changemax_iter. - Mismatch between loss and metric. The default loss is
squared_error, which penalizes large mistakes heavily, but you score with MAE. This is usually fine. If MAE is your real goal, you can tryloss="absolute_error", which is slower but optimizes the metric you report.
Edge cases specific to this dataset
The target MedHouseVal is capped at 5.0 ($500,000), so many expensive districts share exactly that value. No model can predict above the cap, and the errors on those rows are partly an artifact of the data. The same cap also limits how much any model can improve.
Boosting also cannot extrapolate. Trees predict values they saw during training, so a district with an income above the training range gets a prediction like the highest-income group, while a linear model would keep extending its line.
What comes next
You now have two scored candidates: Ridge near 0.5 and boosting near 0.3 MAE. The boosting model wins clearly, so it is the one to tune. The next chapter searches over learning_rate and max_leaf_nodes, which control step size and tree size, with a grid search that uses only the training data.
Exercise
A teammate runs cross_validate on HistGradientBoostingRegressor and gets a mean train MAE of 0.06 and a mean validation MAE of 0.34. What does this say about the model, and name two parameters you would change to address it?
Show answer
The large gap shows overfitting: the model fits its training rows almost perfectly but does not generalize to the held-out fold. Reduce its capacity by lowering maxleafnodes (smaller trees) and lowering maxiter or learningrate so fewer or gentler corrections are made. Early stopping can also help. Check the change by re-running the same cross-validation and looking at whether the validation MAE falls and the gap shrinks.
Exercise
Why does the Ridge model need a StandardScaler in a pipeline but HistGradientBoostingRegressor does not?
Show answer
Ridge penalizes coefficient size, so features on different scales get penalized unevenly, and scaling must be learned from the training fold only, which is why it belongs in a pipeline. Gradient boosting uses trees that compare each feature to a threshold, so any increasing rescaling of a feature produces the same splits and has no effect.