Sub topic 5
Choosing a scoring metric
This chapter assumes you can fit scikit-learn estimators, understand cross-validation as described in the previous chapter, and know the basic classification and regression metrics (accuracy, precision, recall, mean squared error). It covers how the scoring argument controls what a learning curve or validation curve shows.
Why the metric shapes every curve
A learning curve or validation curve is only a plot of a number against another number. The first number is whatever the scorer returns. Change the scorer and the same model on the same data can look underfit, overfit, or fine.
The scorer is applied twice for each fold: once on the training portion and once on the validation portion. The gap between the two curves, the main signal for diagnosing variance, is therefore a gap in that metric. A metric that hides errors you care about hides the problem from your diagnosis too.
Two common ways a metric misleads:
- Saturation. Accuracy on a dataset with 95% negatives gives a score near 0.95 for a model that never predicts the positive class. Both curves sit high and flat, and the gap is small. The plot suggests a healthy model.
- Mismatch with the goal. If missing a positive case is expensive, accuracy can improve while recall gets worse. Curves built on accuracy will not show it.
How `scoring` works in scikit-learn
Both learning_curve and validation_curve take a scoring argument. It accepts a string name, a scorer object, or a callable with the signature scorer(estimator, X, y). If you pass None, the estimator's own score method is used. That means accuracy for classifiers and R² for regressors, which may not be what you want.
Three rules apply to scorers:
- Higher is better. Scorers follow this convention so that tools like
GridSearchCVcan always maximize. Error metrics are therefore exposed with aneg_prefix, such asneg_mean_squared_errorandneg_root_mean_squared_error. The values are negative. To read them as errors, flip the sign before plotting. - One metric per call. Unlike
cross_validate, these two functions accept a single scorer. To compare metrics, call the function once per metric. - Some metrics need more than hard labels.
roc_auc,average_precision, andneg_log_lossusepredict_probaordecision_function. If the estimator has neither, scoring fails.
Here is a table of common choices.
| Task | Metric string | Use it when | Watch out for |
|---|---|---|---|
| Classification | `accuracy` | Classes are balanced and all errors cost the same | Saturates on imbalanced data |
| Classification | `balanced_accuracy` | Classes are imbalanced and you want recall averaged per class | Ignores precision |
| Classification | `f1`, `f1_macro` | You need a balance of precision and recall | Depends on the decision threshold |
| Classification | `roc_auc` | You care about ranking quality across thresholds | Can look good on heavily imbalanced data |
| Classification | `average_precision` | The positive class is rare and precision matters | Baseline equals the positive rate, not 0.5 |
| Classification | `neg_log_loss` | You use predicted probabilities directly | Punishes overconfidence heavily |
| Regression | `neg_root_mean_squared_error` | Large errors should count more, and you want units of the target | Sensitive to outliers |
| Regression | `neg_mean_absolute_error` | You want robustness to outliers | Less smooth to optimize |
| Regression | `r2` | You want a unitless comparison to predicting the mean | Can be misleading across different datasets |
Seeing the effect on an imbalanced problem
The next example builds a dataset with about 5% positives. It computes the same learning curve under four metrics. A DummyClassifier baseline shows what accuracy gives for a model that has learned nothing.
import numpy as np
from sklearn.datasets import make_classification
from sklearn.dummy import DummyClassifier
from sklearn.linear_model import LogisticRegression
from sklearn.model_selection import StratifiedKFold, cross_val_score, learning_curve
X, y = make_classification(
n_samples=2000,
n_features=20,
n_informative=5,
weights=[0.95, 0.05],
flip_y=0.01,
random_state=0,
)
cv = StratifiedKFold(n_splits=5, shuffle=True, random_state=0)
baseline = cross_val_score(DummyClassifier(strategy="most_frequent"), X, y, cv=cv)
print(f"Majority-class accuracy: {baseline.mean():.3f}")
model = LogisticRegression(max_iter=2000)
for scoring in ["accuracy", "balanced_accuracy", "roc_auc", "average_precision"]:
sizes, train_scores, val_scores = learning_curve(
model,
X,
y,
train_sizes=np.linspace(0.2, 1.0, 4),
cv=cv,
scoring=scoring,
)
print(scoring)
print(" train ", np.round(train_scores.mean(axis=1), 3))
print(" validation", np.round(val_scores.mean(axis=1), 3))Run it and compare the output. The accuracy curves sit close to the majority-class baseline and change little as data grows, so they say almost nothing about whether the model has learned the minority class. balanced_accuracy and average_precision show a clearer relationship between training size and validation score. This is the signal you need to decide whether more data would help.
The ranges also differ by metric. A validation average_precision of 0.4 is not "bad" in the way an accuracy of 0.4 is. Its floor is the positive rate, here about 0.05. Always compare a curve to the right baseline for its metric.
Custom scorers and asymmetric costs
When no built-in metric matches your costs, build a scorer with make_scorer. The example below uses F2, which weights recall more heavily than precision. It then draws a validation curve over the regularization strength C of a logistic regression. It reuses X, y, and cv from the previous example.
import numpy as np
from sklearn.linear_model import LogisticRegression
from sklearn.metrics import fbeta_score, make_scorer
from sklearn.model_selection import validation_curve
f2 = make_scorer(fbeta_score, beta=2)
param_range = np.logspace(-3, 2, 6)
train_scores, val_scores = validation_curve(
LogisticRegression(max_iter=2000),
X,
y,
param_name="C",
param_range=param_range,
cv=cv,
scoring=f2,
)
for c, tr, va in zip(param_range, train_scores.mean(axis=1), val_scores.mean(axis=1)):
print(f"C={c:.0e} train={tr:.3f} validation={va:.3f}")If a metric is an error rather than a score, pass greater_is_better=False to make_scorer. It then returns the negated value, matching the built-in neg_ metrics.
The F2 score depends on the decision threshold, which here is the default of 0.5 on the predicted probability. A curve built on a threshold-dependent metric mixes two effects: how well the model ranks examples, and how well the fixed threshold suits it. If the curve moves in a way you did not expect, compare it with a threshold-free metric such as roc_auc or average_precision before concluding the model changed.
Reading negative scores
Regression curves need one extra step. With neg_root_mean_squared_error, the returned arrays hold negative errors. Flip the sign, then read them as errors, where lower is better and the usual picture of training error below validation error applies.
import numpy as np
from sklearn.datasets import load_diabetes
from sklearn.linear_model import Ridge
from sklearn.model_selection import learning_curve
X_reg, y_reg = load_diabetes(return_X_y=True)
sizes, train_scores, val_scores = learning_curve(
Ridge(alpha=1.0),
X_reg,
y_reg,
train_sizes=np.linspace(0.2, 1.0, 5),
cv=5,
scoring="neg_root_mean_squared_error",
)
train_rmse = -train_scores.mean(axis=1)
val_rmse = -val_scores.mean(axis=1)
for n, tr, va in zip(sizes, train_rmse, val_rmse):
print(f"n={n:3d} train RMSE={tr:.1f} validation RMSE={va:.1f}")Forgetting the sign flip is a common source of confusion. A plot of raw neg_ scores looks upside down, with the "training" curve appearing above the validation curve even though training error is lower. That is the same relationship, mirrored. Decide on one convention for your plots and label the axis accordingly, for example "RMSE (lower is better)".
Practical guidance
- Pick the metric before you plot. Choose it from the cost of errors in your application. Do not pick it because it makes the curve look nicer.
- Check a baseline for each metric. Use
DummyClassifierorDummyRegressorthroughcross_val_scorewith the samecvandscoring. A curve is only meaningful relative to what a trivial model scores. - Use the same metric for tuning and diagnosis. If you select hyperparameters with one metric and diagnose fit with another, the two can disagree. A high-variance gap under
neg_log_losscan coexist with a flat accuracy curve, because log loss penalizes confident mistakes that accuracy does not see. - Plot two metrics when unsure. One threshold-free metric (
roc_aucoraverage_precision) and one metric tied to your decision (f1, recall, or an error in target units) is a good pair. If they disagree, the disagreement tells you something about calibration or thresholds.
Exercise
You compute a learning curve for a fraud detector with scoring="accuracy". Fraud is 1% of the data. Both curves sit near 0.99 and are almost flat as the training set grows. A colleague concludes that the model is excellent and that more data will not help. What is wrong with this conclusion, and what would you do to check it?
Show answer
A model that always predicts "not fraud" already scores about 0.99 accuracy, so the flat curves say nothing about whether the model detects fraud. Accuracy is saturated on this data. Compute a DummyClassifier(strategy="most_frequent") baseline with the same cv and scoring to confirm. Then recompute the learning curve with a metric that reflects the rare class, such as average_precision or balanced_accuracy, and compare each curve with its own baseline. Only then can you judge whether the curves converge or still have a gap, which decides whether more data would help.
Exercise
You run learning_curve with scoring="neg_mean_squared_error" and get a training curve around -20 and a validation curve around -45. How do you read these values, and which curve represents the better fit to its data?
Show answer
Flip the sign to get mean squared errors: about 20 on the training folds and about 45 on the validation folds. Lower error is better, so the model fits the training data better than the validation data. The gap of about 25 in MSE is the generalization gap and points toward variance. The neg_ prefix only exists so that higher is always better. The training curve appearing higher on the raw plot is the same relationship, mirrored.