Sub topic 11
Cross-validation for a steadier estimate
A single train/test split gives you one number. That number depends on which rows landed in the test set. Cross-validation repeats the split several times and averages the results, so you get an estimate and a measure of how much it varies. This chapter covers how k-fold cross-validation works, how to run it with cross_val_score, and the errors that make the scores misleading.
This chapter assumes you can fit a LinearRegression, compute R-squared, RMSE and MAE on a held-out set, and build a Pipeline with StandardScaler. If any of those is unfamiliar, review the chapters on metrics and pipelines first.
Why one split is not enough
Suppose you split 442 rows into 353 training rows and 89 test rows. If a few unusual rows fall in the test set, your R-squared looks poor. If they fall in the training set, it may look good. Neither result tells you how the model behaves on new data in general. With small datasets, the swing between random splits can be large.
Cross-validation addresses this by using every row for testing exactly once.
How k-fold cross-validation works
In k-fold cross-validation you divide the data into k parts called folds. For each fold in turn:
- Hold out that fold as the validation set.
- Fit a fresh copy of the model on the other k-1 folds.
- Score the fitted model on the held-out fold.
You end up with k scores. Their mean is your performance estimate, and their standard deviation shows how sensitive the result is to the split.
Each round fits a new model, so k-fold costs roughly k times as much as one fit. For linear models on small or medium data this cost is minor.
Running cross_val_score
cross_val_score does the whole loop. You pass an estimator, the data, the number of folds cv, and a scoring name. The example below puts scaling and Ridge regression in one pipeline.
from sklearn.datasets import load_diabetes
from sklearn.linear_model import Ridge
from sklearn.model_selection import cross_val_score
from sklearn.pipeline import make_pipeline
from sklearn.preprocessing import StandardScaler
X, y = load_diabetes(return_X_y=True)
pipe = make_pipeline(StandardScaler(), Ridge(alpha=1.0))
scores = cross_val_score(pipe, X, y, cv=5, scoring="r2")
print("R2 per fold:", scores)
print("mean:", scores.mean(), "std:", scores.std())The function returns a NumPy array with one score per fold. Report the mean together with the standard deviation. A mean R-squared of 0.48 with a standard deviation of 0.05 is a different statement from the same mean with a standard deviation of 0.20.
Why the pipeline matters
cross_val_score clones the estimator and fits it separately for each fold. Because the scaler is inside the pipeline, it is refit on the training folds only. The validation fold never contributes to the mean and standard deviation used for scaling.
If you scaled the full dataset first and passed the scaled array to the model, the validation rows would influence the scaling parameters. This is data leakage. The scores would be slightly optimistic, and with steps that learn more from the data (feature selection, target encoding) the optimism can be large.
Scoring names and the sign convention
The scoring argument is a string. Scikit-learn's rule is that higher scores are better, so error metrics are negated.
| `scoring` string | Meaning | Sign of returned values |
|---|---|---|
| `"r2"` | R-squared | Higher is better, can be negative |
| `"neg_mean_squared_error"` | Negative MSE | Values are 0 or below |
| `"neg_root_mean_squared_error"` | Negative RMSE | Values are 0 or below |
| `"neg_mean_absolute_error"` | Negative MAE | Values are 0 or below |
To report RMSE in its normal form, flip the sign:
from sklearn.datasets import load_diabetes
from sklearn.linear_model import LinearRegression
from sklearn.model_selection import cross_val_score
X, y = load_diabetes(return_X_y=True)
neg_rmse = cross_val_score(
LinearRegression(), X, y, cv=5, scoring="neg_root_mean_squared_error"
)
rmse = -neg_rmse
print("RMSE per fold:", rmse)
print("mean RMSE:", rmse.mean())If you print the raw values and see negative numbers, that is expected. A common mistake is to read "-55" as a model that is somehow below zero quality, or to pick the model with the most negative score. The best model has the value closest to zero.
Controlling how folds are made
Passing an integer to cv for a regressor uses KFold without shuffling. The folds are consecutive blocks of rows. That is a problem when the rows are sorted, for example by date, by target value, or by group. Each fold then covers a narrow slice of the data, and the scores can be strongly biased.
To shuffle, pass a splitter object explicitly:
from sklearn.datasets import load_diabetes
from sklearn.linear_model import LinearRegression
from sklearn.model_selection import KFold, cross_val_score
X, y = load_diabetes(return_X_y=True)
cv = KFold(n_splits=5, shuffle=True, random_state=0)
scores = cross_val_score(LinearRegression(), X, y, cv=cv, scoring="r2")
print("mean R2:", scores.mean(), "std:", scores.std())Setting random_state makes the folds reproducible. When you compare two models, give both the same splitter object so they are scored on identical folds. Otherwise, part of the difference you see comes from the folds rather than from the models.
Cases that need a different splitter
- Time series. Shuffling lets the model train on the future and predict the past. Use
TimeSeriesSplit, which always validates on rows that come after the training rows. - Grouped rows. If several rows come from the same customer, patient or house, a random split puts related rows in both training and validation. Use
GroupKFoldand passgroups=tocross_val_score. - Classification. Not relevant to regression in this tutorial, but note that scikit-learn switches to
StratifiedKFoldautomatically when the estimator is a classifier.
Choosing k
The value of k trades bias against variance and cost.
- With small k (such as 3), each model trains on less data than the final model will use. The estimate tends to be pessimistic.
- With large k (such as 20, or leave-one-out where k equals the number of rows), the training sets are nearly the full data, so the bias is low. The cost is higher, and the scores from different folds are strongly correlated because the training sets overlap heavily.
- Values of 5 and 10 are common defaults and work well in most cases.
If your dataset has 50 rows, a 5-fold split gives validation folds of 10 rows. Per-fold R-squared computed on 10 rows is noisy. Look at the mean, and do not read much into any single fold.
Getting more than a score
cross_val_score returns only the validation scores. Two related functions cover other needs.
cross_validatereturns a dictionary with fit times, score times, and, if you ask for it, training scores and multiple metrics.cross_val_predictreturns an out-of-fold prediction for every row, which is useful for residual plots.
from sklearn.datasets import load_diabetes
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
X, y = load_diabetes(return_X_y=True)
cv = KFold(n_splits=5, shuffle=True, random_state=0)
pipe = make_pipeline(StandardScaler(), Ridge(alpha=1.0))
res = cross_validate(
pipe,
X,
y,
cv=cv,
scoring=["r2", "neg_mean_absolute_error"],
return_train_score=True,
)
print("train R2:", res["train_r2"].mean())
print("test R2:", res["test_r2"].mean())
print("test MAE:", -res["test_neg_mean_absolute_error"].mean())Comparing the training and test means shows overfitting. A training R-squared far above the test R-squared means the model fits the training rows better than it generalizes. For cross_val_predict, remember that the predictions come from different models, one per fold. Do not treat them as the output of a single fitted model, and do not compute one final metric from them and report it as the same thing as the mean of per-fold scores.
Common errors
- Reporting only the mean. Always include the spread.
- Forgetting the sign of negated metrics. Flip the sign before reporting.
- Leakage from preprocessing outside the pipeline. Keep all learned transformations inside.
- Unshuffled folds on sorted data. Use
KFold(shuffle=True)unless the order carries meaning. - Ignoring grouping or time order. Use
GroupKFoldorTimeSeriesSplit. - Reusing the test set. Cross-validation is for model selection and estimation on the training data. Keep a final test set aside and score it once.
- Treating small differences as real. If two models differ by less than the fold standard deviation, you cannot tell them apart from this evidence alone.
Exercise
You run crossvalscore with scoring="negmeansquared_error" on two pipelines and get mean scores of -3200 for pipeline A and -2900 for pipeline B. Which pipeline has the lower error, and what is the approximate RMSE of that pipeline? Also, why must the StandardScaler be inside each pipeline rather than applied to X beforehand?
Show answer
Pipeline B has the lower error, because -2900 is closer to zero than -3200. Its MSE is about 2900, so its RMSE is about sqrt(2900), roughly 53.9. (Strictly, the square root of the mean MSE is not the mean of per-fold RMSE values, but it is a reasonable approximation.) The scaler must be inside the pipeline so that crossvalscore refits it on the training folds of each round. If you scale X beforehand, the validation rows influence the mean and standard deviation, which leaks information and makes the scores optimistic.
Exercise
A dataset of house sales is sorted by sale date, and each row includes a house ID. Some houses appear several times. Which splitter would you choose for predicting future prices, and which one for estimating performance on houses the model has never seen?
Show answer
For predicting future prices, use TimeSeriesSplit so validation rows always come after the training rows. For performance on unseen houses, use GroupKFold with the house ID passed as groups, so all rows from one house stay on the same side of each split.