Sub topic 10
Comparing models with cross-validation
This chapter assumes you have loaded the California housing data, made a train/test split with random_state=42, and set a baseline. It also assumes you know how a scikit-learn pipeline works. If you skipped those steps, run the earlier chapters' code first so that X_train, y_train, and df exist.
Why one split is not enough
A single validation split gives one score. That score depends on which rows landed in the validation set, so a small difference between two models may be luck. Cross-validation repeats the evaluation several times on different slices of the training data and averages the results. You get a more stable estimate, and you also see how much the score varies.
The test set stays untouched. All model comparison happens inside the training data.
How 5-fold cross-validation works
With cv=5, scikit-learn cuts the training set into five equal folds. It trains on four folds, scores on the fifth, and repeats until each fold has been the validation fold once.
Scoring Ridge with a pipeline
Scaling must happen inside each round. If you scaled the whole training set first, the validation fold would influence the mean and standard deviation used to scale the training folds. That is leakage. A pipeline refits the scaler on the training folds of each round only.
from sklearn.datasets import fetch_california_housing
from sklearn.model_selection import train_test_split, cross_val_score
from sklearn.pipeline import make_pipeline
from sklearn.preprocessing import StandardScaler
from sklearn.linear_model import Ridge
df = fetch_california_housing(as_frame=True).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
)
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("Ridge CV MAE:", -scores.mean())Why the scores are negative
Scikit-learn's tools assume that a larger score is better. Error metrics are the opposite, so the library reports the negated error, such as neg_mean_absolute_error. Flip the sign before you report it. The values are in units of $100,000, so an MAE of 0.5 means about $50,000.
Scoring gradient boosting the same way
Use the same data, the same cv, and the same metric. Only then are the numbers comparable. HistGradientBoostingRegressor models non-linear relationships and does not need scaling, so it goes in without a scaler.
from sklearn.ensemble import HistGradientBoostingRegressor
from sklearn.model_selection import cross_val_score
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())Run both snippets and compare them with the baseline MAE. Ridge should beat the baseline clearly. Gradient boosting should beat Ridge, because house value depends on location and income in non-linear ways that a straight-line model cannot capture.
Common errors
- Fitting the scaler on all of
X_trainbefore callingcross_val_score. Put it in the pipeline instead. - Comparing models with different
cvvalues or metrics. - Forgetting the minus sign, which makes an error look like a negative number.
- Looking at the test set to choose between models. That uses up your honest estimate.
- Reading a small gap between means as a clear win. Use
scores.std()to see the spread across folds.
Exercise
Your Ridge pipeline's cross_val_score call returns an average of -0.53 with scoring="neg_mean_absolute_error". What is the MAE in dollars, and why is the number negative?
Show answer
The MAE is 0.53 in units of $100,000, so about $53,000. The value is negative because scikit-learn maximizes scores, so error metrics are reported as the negated error. Multiply by -1 to get the MAE.
Exercise
A colleague runs StandardScaler().fit_transform(X_train) and then passes the result to cross_val_score with a plain Ridge. What is wrong, and how do you fix it?
Show answer
The scaler has seen every fold, including each round's validation fold, so its mean and standard deviation leak validation information into training. Use make_pipeline(StandardScaler(), Ridge()) and pass the unscaled X_train, so the scaler is refit on the training folds of each round.