Sub topic 4
Scoring and reporting fold results
This chapter assumes you know how k-fold splitting works, can use scikit-learn's fit and predict, and know accuracy, precision, recall and ROC AUC. Here you will learn how to turn k fold scores into a number you can report, and how to describe how far to trust it.
From folds to one number
Each fold gives one score, so k-fold gives you k scores. The usual summary is the mean of those scores. The spread across folds shows how much the score changes when the training and test data change.
Choosing a scoring metric
The scoring argument decides what each fold measures. If you leave it out, scikit-learn uses the estimator's default. That is accuracy for classifiers and R² for regressors. Pick the metric before you run anything, based on what the model is for.
| Task | Common `scoring` values |
|---|---|
| Balanced classification | `"accuracy"` |
| Imbalanced classification | `"f1"`, `"balanced_accuracy"`, `"average_precision"` |
| Ranking by probability | `"roc_auc"` |
| Regression | `"neg_mean_absolute_error"`, `"r2"` |
Error metrics carry a neg_ prefix. scikit-learn assumes that a higher score is better, so it negates losses. A result of -0.42 for neg_mean_absolute_error means a mean absolute error of 0.42.
Several metrics in one run
cross_val_score returns one metric. Use cross_validate when you want several metrics, or timings, from a single set of fits.
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)
print(sorted(results.keys()))
for name in metrics:
scores = results[f"test_{name}"]
print(f"{name:9s} mean={scores.mean():.3f} std={scores.std(ddof=1):.3f}")The result is a dictionary. It holds fit_time and score_time, plus one test_<metric> array for each metric. Each array has one entry per fold. Add return_train_score=True to also get train_<metric> arrays. A large gap between train and test scores points to overfitting.
Reporting the spread
Report the mean together with a measure of spread. A mean alone hides how unstable the estimate is.
- Standard deviation describes how much the fold scores vary. Use
std(ddof=1), the sample standard deviation. NumPy's defaultstd()divides by k and slightly understates the spread for small k. - Per-fold scores are worth printing when k is small, because five numbers are easy to read.
- Standard error is
std / sqrt(k). It is tempting to treat it as a confidence interval, but you shouldn't.
A fair report looks like this: "5-fold stratified CV, F1 = 0.97 ± 0.01 (mean ± sample std)." State the splitter, k, the metric and the seed, so another person can reproduce the number.
Common errors
- Averaging the wrong thing. The mean of per-fold F1 scores is not the F1 of all the predictions pooled together. Both are valid, but they differ, especially when fold sizes or class counts differ. Pick one and say which.
- Comparing models on different splits. Fix
random_stateon the splitter, and reuse the samecvobject for every model. Then the models are tested on the same folds, and the comparison is fairer. - Ignoring tiny differences. If two models differ by less than the fold-to-fold std, you can't say one is better from this evidence alone.
- Choosing the metric after seeing results. This quietly biases the report. Fix the metric first.
Exercise
A 5-fold run of cross_validate with scoring="neg_mean_absolute_error" gives test_score values with a mean of -2.0 and a sample std of 0.5. What is the mean absolute error, and how would you report it?
Show answer
The mean absolute error is 2.0, because the sign is only scikit-learn's convention that higher is better. Report it as "MAE = 2.0 ± 0.5 (mean ± sample std over 5 folds)", and name the splitter and the seed.