Sub topic 11
Cross-validation for a steadier estimate
This chapter assumes you can fit a LinearRegression, split data with train_test_split, compute R-squared and RMSE, and build a Pipeline with a scaler. It covers why one split gives a noisy score and how cross_val_score gives a steadier one.
Why one split is not enough
A single train_test_split produces one score. That score depends on which rows landed in the test set. A different random_state can give a noticeably different R-squared, especially on small datasets. You cannot tell whether a difference between two models is real or just luck of the split.
Cross-validation reduces this problem by repeating the split several times and averaging.
How k-fold cross-validation works
In k-fold cross-validation, the data is divided into k equal parts called folds. The model is trained k times. Each time, one fold is the test set and the other k-1 folds are the training set. You get k scores, one per fold.
Running cross_val_score
Pass the whole estimator, the full feature matrix and target, the number of folds, and a scoring name. Put the scaler inside a pipeline so it is refit on each training fold. If you scale the full dataset first, information from the test fold leaks into training.
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 mean is your performance estimate. The standard deviation shows how much the score moves between folds. If two models have means of 0.48 and 0.49 and a standard deviation of 0.05, they are effectively tied.
Choosing the scoring argument
Scorers follow a "higher is better" rule. Error metrics are therefore negated.
| Goal | `scoring` value | Note |
|---|---|---|
| R-squared | `"r2"` | Default for regressors |
| RMSE | `"neg_root_mean_squared_error"` | Multiply by -1 to read it |
| MAE | `"neg_mean_absolute_error"` | Multiply by -1 to read it |
| MSE | `"neg_mean_squared_error"` | Multiply by -1 to read it |
Common errors
- Fitting the scaler before cross-validation. This leaks test-fold statistics into training. Use a pipeline.
- Reading negative scores as bad.
neg_root_mean_squared_errorreturns values like -55. Flip the sign to get an RMSE of 55. - Ordered data with plain k-fold. With an integer
cvon a regressor, scikit-learn usesKFoldwithout shuffling. If rows are sorted, for example by date or by target, folds are unrepresentative. PassKFold(n_splits=5, shuffle=True, random_state=0)ascvfor sorted data that is not a time series. For time series, useTimeSeriesSplit. - Treating the CV score as a final test score. If you tune choices against it repeatedly, it becomes optimistic. Keep a final held-out test set for one last check.
Exercise
You run crossvalscore with scoring="negmeanabsolute_error" and cv=5, and get a mean of -3.2 with a standard deviation of 0.4. What is the MAE estimate, and what does the standard deviation tell you?
Show answer
The MAE estimate is 3.2, because you flip the sign of the negated score. The standard deviation of 0.4 shows how much the MAE varies between folds. Differences between models smaller than about that amount are not reliable evidence that one model is better.