Sub topic 4
Scoring and Reporting Fold Results
This chapter assumes you can run k-fold cross-validation with scikit-learn (the previous chapter) and know basic metrics such as accuracy, precision, recall, and mean squared error. It covers three things: choosing the metric that each fold computes, collecting the per-fold numbers, and summarizing them honestly.
What a fold score is
Cross-validation with k folds produces k separate test scores. Each score comes from a model trained on the other k-1 folds and evaluated on its own held-out fold. The scores differ because each fold has different test samples and a slightly different training set. That variation is information, and a single averaged number hides it.
Choosing the scoring metric
The scoring argument tells scikit-learn which metric to compute on each fold. If you leave it out, cross_val_score uses the estimator's own score method. For classifiers that is accuracy, and for regressors it is R². This default is easy to forget, so state the metric explicitly.
Common choices:
| Task | `scoring` string | Notes |
|---|---|---|
| Classification | `"accuracy"` | Misleading when classes are imbalanced |
| Classification | `"f1"`, `"precision"`, `"recall"` | Binary by default. Multiclass needs a suffix such as `"f1_macro"` |
| Classification | `"roc_auc"` | Uses `predict_proba` or `decision_function`, not hard labels |
| Regression | `"r2"` | Regressor default. Can be negative on a bad fold |
| Regression | `"neg_mean_squared_error"`, `"neg_mean_absolute_error"` | Negated, see below |
Choose the metric from the cost of mistakes in your application, not from habit. A fraud detector with 1% positives can reach 99% accuracy by predicting "not fraud" every time. Its recall is zero, and a recall or F1 fold score shows that.
Why error metrics are negative
Scikit-learn's model-selection tools assume that a higher score is better. Error metrics are lower-is-better, so the library negates them. A neg_mean_absolute_error of -3.2 means a mean absolute error of 3.2. Flip the sign before you report it.
from sklearn.datasets import load_diabetes
from sklearn.linear_model import Ridge
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)
neg_mae = cross_val_score(Ridge(alpha=1.0), X, y, cv=cv,
scoring="neg_mean_absolute_error")
mae = -neg_mae # convert back to an ordinary error
print("per-fold MAE:", mae.round(1))
print(f"MAE = {mae.mean():.1f} +/- {mae.std(ddof=1):.1f}")Collecting several metrics at once
cross_val_score returns one metric. When you want several, cross_validate fits each fold once and scores it with every metric. This is cheaper than calling cross_val_score several times. It also returns fit and score times, and with return_train_score=True it returns training-fold scores too.
from sklearn.datasets import load_breast_cancer
from sklearn.linear_model import LogisticRegression
from sklearn.model_selection import StratifiedKFold, cross_validate
from sklearn.pipeline import make_pipeline
from sklearn.preprocessing import StandardScaler
X, y = load_breast_cancer(return_X_y=True)
model = make_pipeline(StandardScaler(), LogisticRegression(max_iter=1000))
cv = StratifiedKFold(n_splits=5, shuffle=True, random_state=0)
metrics = ["accuracy", "f1", "roc_auc"]
results = cross_validate(model, X, y, cv=cv,
scoring=metrics, return_train_score=True)
for name in metrics:
test = results[f"test_{name}"]
train = results[f"train_{name}"]
print(f"{name:9s} test={test.mean():.3f} +/- {test.std(ddof=1):.3f}"
f" train={train.mean():.3f}")
print("mean fit time (s):", results["fit_time"].mean().round(4))The result is a dictionary. Its keys are fit_time, score_time, and test_<metric>. With return_train_score=True it also has train_<metric>. Each value is an array of length k.
Comparing train and test scores is a quick diagnostic:
- A large gap, such as train 1.00 against test 0.85, points to overfitting.
- Low scores on both point to underfitting.
- Computing training scores adds cost, so turn them on only when you want this diagnostic.
Summarizing the folds: mean and spread
Two numbers are the minimum: the mean and a measure of spread.
- Mean. The average of the k fold scores. It is your point estimate of generalization performance.
- Standard deviation. Describes how much the fold scores vary. Use
ddof=1(sample standard deviation) when you report it, since k is small. NumPy's defaultddof=0slightly understates the spread.
Always say which one you mean. Write "accuracy 0.972 ± 0.011 (mean ± std over 5 folds)", not "0.972 ± 0.011".
Be careful with the standard error
It is tempting to divide the standard deviation by √k to get a standard error and a tight confidence interval. Don't. The k training sets overlap heavily, and each sample is tested exactly once, so the fold scores are positively correlated. They are not independent draws. Statistical results show that no unbiased estimator of the variance of k-fold cross-validation exists. A std / sqrt(k) interval is usually too narrow.
Practical guidance:
- Report the standard deviation across folds as a description of variability, not as a confidence interval.
- When comparing two models, evaluate both on identical folds (same
cvobject with a fixedrandom_state). Then compare them fold by fold. - If the difference between models is smaller than the fold-to-fold spread, treat the models as indistinguishable.
- For a more stable estimate, use repeated cross-validation (a later chapter).
Averaging per fold or pooling predictions
There are two ways to turn k folds into one number.
- Per-fold averaging. Compute the metric on each fold and average. This is what
cross_val_scoredoes. It gives you the spread for free. - Pooling. Collect out-of-fold predictions for every sample with
cross_val_predict, then compute one metric on the combined predictions.
Per-fold averaging is the default choice. Pooled predictions are handy for confusion matrices and calibration plots, and they come from a model that never saw that sample. Pooling has drawbacks:
- Predictions from different fold models are mixed together.
- You lose the fold-level spread.
- Metrics such as ROC AUC can behave differently when scores from different models are merged, because the models' score scales may not match.
Use pooled predictions to inspect errors, and use per-fold scores to report performance.
If the folds differ in size (for example, 103 samples in 5 folds), the plain mean gives slightly more weight per sample to smaller folds. The difference is usually negligible. With very uneven folds, such as in grouped splitting, weight each fold by its test size.
Custom scorers and failed folds
When no built-in string fits, wrap any metric with make_scorer. The example below scores F-beta with beta = 2, which values recall more than precision.
from sklearn.datasets import load_breast_cancer
from sklearn.linear_model import LogisticRegression
from sklearn.metrics import fbeta_score, make_scorer
from sklearn.model_selection import StratifiedKFold, cross_val_score
from sklearn.pipeline import make_pipeline
from sklearn.preprocessing import StandardScaler
X, y = load_breast_cancer(return_X_y=True)
model = make_pipeline(StandardScaler(), LogisticRegression(max_iter=1000))
cv = StratifiedKFold(n_splits=5, shuffle=True, random_state=0)
f2 = make_scorer(fbeta_score, beta=2)
scores = cross_val_score(model, X, y, cv=cv, scoring=f2)
print(scores.round(3), f"mean={scores.mean():.3f}")For an error metric, pass greater_is_better=False so that the scorer negates it, in line with the library convention.
Sometimes a fold fails, for instance because a rare class is missing from a training fold. By default, error_score=np.nan records NaN for that fold and emits a warning. If you then call .mean(), the result is NaN, which is at least visible. Do not quietly use np.nanmean and report the result as if k folds had run. State how many folds succeeded, or fix the cause, for example with stratified splitting.
What to include in a report
A complete report of cross-validation results contains:
- The metric name and direction (higher or lower is better).
- The splitting scheme and k, such as "stratified 5-fold, shuffled, seed 0".
- The mean and the spread, with the kind of spread named.
- The individual fold scores when k is small. Five numbers are easy to show.
- The dataset size and, for classification, the class balance.
- A baseline for context, such as a majority-class classifier or a mean predictor, scored with the same folds.
The baseline matters more than it looks. An accuracy of 0.93 sounds strong until you see that the majority-class predictor scores 0.91 on the same folds.
Common mistakes
- Reporting the best fold. Picking the highest of k scores is cherry-picking. Report the mean.
- Reusing the CV score after tuning. If you chose hyperparameters by maximizing the same cross-validation score, that score is optimistic. Nested cross-validation, covered later, fixes this.
- Mixing metrics across models. Compare models with the same metric on the same splits.
- Ignoring the direction of
neg_metrics. The "best" model byneg_mean_squared_erroris the one closest to zero, meaning the largest value.
Exercise
You run 5-fold cross-validation with scoring="negrootmeansquarederror" and get the scores [-4.1, -3.8, -4.4, -3.9, -4.3]. What do you report as the result, including its sign and the spread? Then explain why dividing the standard deviation by the square root of 5 is not a reliable confidence interval.
Show answer
Flip the sign to get RMSE values [4.1, 3.8, 4.4, 3.9, 4.3]. The mean is 4.10. The sample standard deviation (ddof=1) is about 0.26. Report "RMSE = 4.10 ± 0.26 (mean ± std over 5 folds)". Dividing by √5 treats the folds as independent, but the training sets overlap and the fold scores are correlated. The resulting interval would be too narrow, and no unbiased variance estimator exists for k-fold cross-validation. So report the standard deviation as a description of variability, not as a confidence interval.
Exercise
A fraud-detection dataset has 2% positive cases. Cross-validated accuracy is 0.98 ± 0.00 for your model. What should you check next, and with which scoring options?
Show answer
Compare against a majority-class baseline on the same folds. It would also score about 0.98, so accuracy shows no skill. Re-run with crossvalidate using scoring such as ["recall", "precision", "f1", "rocauc"] (or "average_precision") and use stratified folds so each fold contains positive cases. Then report per-fold recall and precision with their spread.