Sub topic 3
Choosing a metric that matches the goal
A metric turns a model's predictions into one number you can compare. Every later choice in this tutorial (model family, hyperparameters, final pick) is judged by that number. If the metric doesn't reflect what the business or user cares about, you can win the comparison and still ship the wrong model.
This chapter assumes you can fit a scikit-learn estimator, know what a confusion matrix is, and have read the earlier chapter on framing the problem. You should already know whether the task is classification or regression.
Start from the cost of mistakes
Ask three questions before you pick a metric.
- What decision does the prediction feed? A ranked worklist, an automatic approval, and a forecast used for planning need different numbers.
- What does each kind of error cost? A missed fraud case and a false alarm rarely cost the same.
- Does the output need to be a calibrated probability, or only a good ordering or label?
The answers separate three families of metrics:
- Threshold metrics score hard labels: accuracy, precision, recall, F1.
- Ranking metrics score how well the model orders rows: ROC AUC, average precision.
- Probability metrics score the predicted probabilities themselves: log loss, Brier score.
Classification metrics
Accuracy and why it misleads
Accuracy is the share of rows predicted correctly. With 5% positives, a model that always predicts "negative" scores 95% and finds no positives. Use accuracy only when classes are roughly balanced and both error types cost about the same.
Precision, recall, and F1
Precision is the share of predicted positives that are truly positive. Recall is the share of true positives the model finds. They trade off against each other through the decision threshold.
- Choose recall when a miss is expensive, such as screening for a disease.
- Choose precision when a false alarm is expensive, such as blocking a legitimate payment.
- F1 is the harmonic mean of the two. It is a reasonable single number when you truly weight them equally, which is rarer than people assume.
fbeta_scorelets you weight recall more (beta above 1) or precision more (beta below 1).
ROC AUC and average precision
ROC AUC is the probability that a random positive row gets a higher score than a random negative row. It doesn't depend on a threshold, and 0.5 means random ordering.
When positives are rare, ROC AUC can look good even though the model is weak at the top of the ranking. The false positive rate divides by the large negative count, so many false positives barely move it. Average precision summarizes the precision-recall curve and is more sensitive in that setting. Its random baseline equals the positive rate, not 0.5, so always compare it to that baseline.
Log loss and Brier score
Log loss and the Brier score reward probabilities that are both accurate and honest. A model with the same ROC AUC as another can have much worse log loss if its probabilities are overconfident. Use them when probabilities feed expected-value calculations, risk scores, or pricing. Lower is better for both. scikit-learn's scorer strings are negated (neg_log_loss, neg_brier_score) so that higher is always better.
Comparing several metrics on identical folds
This example builds an imbalanced problem and scores a dummy baseline and a logistic regression on the same stratified folds. Watch how accuracy hides the difference that the other metrics expose.
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_validate
from sklearn.pipeline import make_pipeline
from sklearn.preprocessing import StandardScaler
X, y = make_classification(
n_samples=2000, n_features=10, n_informative=4,
weights=[0.95, 0.05], random_state=0,
)
print("positive rate:", y.mean().round(3))
cv = StratifiedKFold(n_splits=5, shuffle=True, random_state=0)
scoring = ["accuracy", "roc_auc", "average_precision", "neg_log_loss", "neg_brier_score"]
models = {
"baseline": DummyClassifier(strategy="prior"),
"logreg": make_pipeline(StandardScaler(), LogisticRegression(max_iter=1000)),
}
for name, model in models.items():
res = cross_validate(model, X, y, cv=cv, scoring=scoring)
row = {m: res[f"test_{m}"].mean().round(3) for m in scoring}
print(name, row)The baseline reaches about 0.95 accuracy with a ROC AUC of 0.5. The logistic regression gains only a little in accuracy, but its average precision is far above the 0.05 floor. Accuracy alone would suggest almost no progress.
Choosing and tuning a threshold
Most classifiers output a probability, and predict cuts it at 0.5. That cut is a default and has no special meaning. If you know the relative costs, you can pick the threshold that minimizes expected cost.
The code below gets out-of-fold probabilities, so each row is predicted by a model that never saw it. It then scans thresholds under an assumed cost of 50 per missed positive and 5 per false alarm.
import numpy as np
from sklearn.datasets import make_classification
from sklearn.linear_model import LogisticRegression
from sklearn.model_selection import StratifiedKFold, cross_val_predict
from sklearn.pipeline import make_pipeline
from sklearn.preprocessing import StandardScaler
X, y = make_classification(
n_samples=2000, n_features=10, n_informative=4,
weights=[0.95, 0.05], random_state=0,
)
cv = StratifiedKFold(n_splits=5, shuffle=True, random_state=0)
model = make_pipeline(StandardScaler(), LogisticRegression(max_iter=1000))
proba = cross_val_predict(model, X, y, cv=cv, method="predict_proba")[:, 1]
cost_fn, cost_fp = 50, 5
thresholds = np.linspace(0.01, 0.99, 99)
costs = []
for t in thresholds:
pred = proba >= t
fn = np.sum(~pred & (y == 1))
fp = np.sum(pred & (y == 0))
costs.append(cost_fn * fn + cost_fp * fp)
best = thresholds[int(np.argmin(costs))]
print("best threshold:", best.round(2))
print("cost at best:", min(costs), "cost at 0.5:", costs[49])The best threshold is well below 0.5, because a miss costs ten times a false alarm. Choosing the threshold on the same predictions you report is itself a form of tuning. Treat it as a hyperparameter and keep it out of the final test estimate, a point the tuning chapter develops.
Regression metrics
Regression metrics differ mainly in how they treat large errors and what units they report.
| Metric | What it measures | Strength | Watch out for |
|---|---|---|---|
| MAE | Average absolute error | Same units as the target, robust to outliers | Treats a big miss like many small ones |
| RMSE | Square root of mean squared error | Penalizes large errors heavily | Dominated by a few outliers |
| R² | Share of variance explained vs. predicting the mean | Scale-free, easy to compare across targets | Can be negative; says nothing about error size in real units |
| MAPE | Average percentage error | Intuitive to non-technical readers | Undefined at zero targets; favors under-prediction |
Pick RMSE when large errors are disproportionately bad, such as capacity planning. Pick MAE when every unit of error costs the same, such as delivery times. For targets spanning orders of magnitude, such as prices, consider a relative error or fitting on the log of the target, and state which scale the metric uses.
Common errors
- Optimizing one metric and reporting another. If you tune for ROC AUC and then quote accuracy, you are comparing models on a number you never optimized.
- Using
predictlabels where a ranking or probability metric needs scores. Passing hard labels to ROC AUC collapses the curve to a single point and understates the model. - Ignoring the spread across folds. A difference of 0.003 with a fold standard deviation of 0.02 is noise.
- Choosing a metric after seeing results. Fix the metric before you compare models, or you will pick the one that flatters your favorite.
- Averaging F1 across classes without knowing how. In multiclass problems, macro averaging weights classes equally, micro averaging weights rows equally, and weighted averaging sits in between. State which one you use.
Summary of the working model
Start with the decision and the cost of errors. Use ranking or probability metrics to compare models, since they don't depend on a threshold. Use threshold metrics or expected cost once you know the action the prediction triggers. Always compare against the baseline score, and always compute every metric on the same folds so differences come from the models.
Exercise
A hospital model flags patients who may need a follow-up test. About 2% of patients need one. A missed patient is much worse than an unnecessary follow-up. The team reports 98% accuracy for a model that never flags anyone. Which metrics would you use to compare candidate models, and what would you do with the decision threshold?
Show answer
Accuracy is useless here, because always predicting "no follow-up" scores 98%. Compare models with a threshold-free ranking metric such as average precision (baseline 0.02), and add recall at the threshold you would actually deploy. If probabilities will be shown to clinicians, also check log loss or the Brier score. Because a miss costs more than a false alarm, lower the threshold below 0.5, choosing it by minimizing expected cost or by requiring a minimum recall, using out-of-fold predictions.
Exercise
Model A has RMSE 12.0 and MAE 8.0. Model B has RMSE 14.0 and MAE 7.0 on the same folds. Late deliveries beyond a large margin cause refunds. Which model do you prefer and why?
Show answer
Prefer Model A. Its RMSE is lower, which means it makes fewer very large errors, and large misses are what trigger refunds. Model B is better on typical error (MAE), but its higher RMSE shows a heavier tail of big mistakes. If every unit of error cost the same, Model B would win.