Sub topic 10
Comparing models with cross-validation
This chapter assumes you have the objects from earlier chapters: df, X_train, X_test, y_train, y_test, and a fitted baseline. You should know what a pipeline is and why the test set stays untouched until the end. The code below recreates the setup so each block runs on its own.
Why one score is not enough
You could fit Ridge and gradient boosting on the training set and score both on the test set. That would break the rule from the splitting chapter. Each time you look at test results and change something, the test set becomes part of your modeling process, and its score stops being an honest estimate.
You could instead hold out a validation set from the training data. That works, but one split gives one number, and that number depends on which rows landed in the validation part. A small gap between two models might come from the split alone.
Cross-validation fixes both problems. It splits the training data into several folds, trains on all but one fold, and scores on the held-out fold. It repeats this until every fold has been held out once. You get several scores per model, and you can look at their mean and spread.
Setup
This block loads the data and recreates the split with the same seed as before.
from sklearn.datasets import fetch_california_housing
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
)Scoring one model with cross_val_score
cross_val_score takes an unfitted estimator, the training data, and a number of folds. It clones the estimator for each fold, so the original object is never fitted.
from sklearn.pipeline import make_pipeline
from sklearn.preprocessing import StandardScaler
from sklearn.linear_model import Ridge
from sklearn.model_selection import cross_val_score
ridge = make_pipeline(StandardScaler(), Ridge(alpha=1.0))
scores = cross_val_score(
ridge, X_train, y_train, cv=5, scoring="neg_mean_absolute_error"
)
print("Fold scores:", scores)
print("Ridge CV MAE:", -scores.mean())Two details matter here.
- The sign is flipped. Scikit-learn's model-selection tools always maximize a score. Error metrics are "lower is better", so the library negates them. The scorer name
neg_mean_absolute_errorreturns values like-0.53. Negate the mean to get the MAE back. - The scaler is inside the pipeline. On every round, the pipeline fits
StandardScaleron the four training folds only, then applies it to the validation fold. If you had scaledX_trainbefore callingcross_val_score, the scaler would have seen the validation rows' means and standard deviations. That is the leakage described in the leakage chapter, now happening inside cross-validation.
What `cv=5` really does
When you pass an integer for a regressor, scikit-learn uses KFold(n_splits=5) without shuffling. The folds are consecutive blocks of rows in the order they appear in the data. That is risky if the rows are sorted by something, such as date, region, or the target. The California housing rows are not in a random order, and a fold made of one contiguous block can contain a different mix of districts from the rest.
For comparing models, make the splitter explicit. Shuffle the rows once, and reuse the same splitter object for every model.
from sklearn.model_selection import KFold
cv = KFold(n_splits=5, shuffle=True, random_state=42)Using one cv object means every model sees identical train/validation partitions. Differences between models then come from the models, not from different folds.
Comparing several models fairly
cross_validate is the multi-metric sibling of cross_val_score. It returns a dictionary with fit times, score times, and one array per metric. You can also ask for training scores, which help you spot overfitting.
import pandas as pd
from sklearn.dummy import DummyRegressor
from sklearn.ensemble import HistGradientBoostingRegressor
from sklearn.linear_model import Ridge
from sklearn.model_selection import KFold, cross_validate
from sklearn.pipeline import make_pipeline
from sklearn.preprocessing import StandardScaler
cv = KFold(n_splits=5, shuffle=True, random_state=42)
models = {
"baseline (mean)": DummyRegressor(strategy="mean"),
"ridge": make_pipeline(StandardScaler(), Ridge(alpha=1.0)),
"hist gradient boosting": HistGradientBoostingRegressor(random_state=42),
}
scoring = {"mae": "neg_mean_absolute_error", "r2": "r2"}
rows = []
for name, model in models.items():
result = cross_validate(
model, X_train, y_train, cv=cv, scoring=scoring, return_train_score=True
)
rows.append(
{
"model": name,
"val_mae": -result["test_mae"].mean(),
"val_mae_std": result["test_mae"].std(),
"train_mae": -result["train_mae"].mean(),
"val_r2": result["test_r2"].mean(),
"fit_seconds": result["fit_time"].mean(),
}
)
print(pd.DataFrame(rows).round(3).to_string(index=False))Note that cross_validate names its keys test_<metric>, even though these are validation folds. The word "test" there means "the held-out part of this split". It has nothing to do with your X_test.
Your numbers will vary slightly by library version and hardware. Typical results look like this:
| Model | Validation MAE | Validation R² | Reading |
|---|---|---|---|
| Baseline (mean) | about 0.91 | about 0.00 | Predicts one value for every district |
| Ridge | about 0.53 | about 0.60 | A linear fit explains most of the gap |
| Histogram gradient boosting | about 0.32 | about 0.84 | Captures non-linear effects such as location |
MAE is in units of $100,000, so a validation MAE of 0.32 means the typical error is around $32,000.
Reading the results
Look at four things, not only the mean.
- Mean against the baseline. A model that cannot beat the baseline has learned nothing useful. Ridge and boosting both clear it by a wide margin here.
- Spread across folds. The standard deviation tells you how much a score moves with the data. If two models differ by less than about one standard deviation, you cannot claim one is better. Here the gap between Ridge and boosting is many times larger than the fold-to-fold spread, so the ranking is reliable.
- Training score against validation score. A training MAE far below the validation MAE signals overfitting. Gradient boosting usually shows a visible gap. Ridge shows almost none. A small gap with a poor score signals underfitting, which is what a linear model does on data with non-linear structure.
- Fit time. Boosting costs much more than Ridge. On this dataset the cost is small, but on larger data it can drive the choice.
Common errors
- Preprocessing outside the pipeline. Fitting a scaler, imputer, or encoder on the full training set before cross-validation leaks validation statistics into every fold. Put every step that learns from data inside the pipeline.
- Forgetting the sign. Printing
scores.mean()for aneg_scorer gives a negative number. Reporting-0.53as "MAE" is a bug. - Comparing models on different folds. Without a shared splitter, a lucky split can flip a close comparison.
- Using
cv=5on ordered data. Shuffle withKFold(shuffle=True). For time series, useTimeSeriesSplitinstead, because shuffling would let the model train on the future. - Touching the test set to break a tie. If two models are close, choose on cost, simplicity, or more cross-validation. Do not peek at
X_test. - Calling
cross_val_scoreand expecting a fitted model. It fits clones and discards them. To get a model for prediction, call.fit(X_train, y_train)afterward.
Choosing the number of folds
Five or ten folds are the usual choices. More folds mean each model trains on more data per round, so the estimate is less pessimistic, but you pay with more fits. With 16,512 training rows, five folds already give each model about 13,200 rows per round. That is plenty.
What comes next
Gradient boosting wins on validation error, so it is the model to tune. The next chapter searches over its hyperparameters with GridSearchCV, which runs this same cross-validation loop once per parameter combination.
Exercise
You run crossvalscore on a pipeline with scoring="negmeanabsoluteerror" and get the fold scores [-0.34, -0.31, -0.33, -0.30, -0.32]. What is the cross-validated MAE, and what does a spread this small tell you? Then explain why scaling the data with StandardScaler before calling crossval_score on a bare model would be a mistake.
Show answer
The mean of the scores is -0.32, so the cross-validated MAE is 0.32 (about $32,000, since the target is in units of $100,000). The scores differ by only a few hundredths, so the estimate is stable and does not depend much on which rows fall in the validation fold. Scaling beforehand is a mistake because the scaler would be fitted on all training rows, including each round's validation fold. Information about the validation data (its mean and standard deviation) then leaks into training, which makes scores look slightly better than they should. Putting the scaler in a pipeline refits it on the training folds of each round only.
Exercise
In the comparison table, Ridge has a validation MAE of 0.53 with a standard deviation of 0.01, and a new model scores 0.52 with a standard deviation of 0.01. Should you conclude the new model is better? What could you do to check?
Show answer
No. The difference of 0.01 is about one standard deviation, so it could come from the choice of folds. To check, use more folds or repeated cross-validation (for example RepeatedKFold), compare the per-fold scores of both models on identical folds, and consider cost and simplicity. If the models are still indistinguishable, prefer the simpler or faster one. Do not use the test set to decide.