Which metric
A metric turns “is the model good?” into a number. Choose it from the decision the model supports, before you train anything: what does an error cost, and which errors cost most? This guide maps task and business goal to a metric, gives its formula and scikit-learn name, and shows when it misleads.
flowchart TD
A{"Task?"} -->|regression| R{"Which errors hurt?"}
R -->|"all units alike"| R1["MAE"]
R -->|"big misses most"| R2["RMSE"]
R -->|"relative, y above 0"| R3["MAPE / RMSLE"]
A -->|classification| C{"What is the output used for?"}
C -->|"probabilities"| C1["log loss, Brier,<br/>calibration curve"]
C -->|"a ranking"| C2{"Rare positives?"}
C2 -->|yes| C3["average precision,<br/>precision at k"]
C2 -->|no| C4["ROC-AUC"]
C -->|"yes/no decisions"| C5{"Error costs known?"}
C5 -->|yes| C6["expected cost<br/>at a tuned threshold"]
C5 -->|no| C7["F1, or recall at<br/>a fixed precision"]
A -->|forecast| F["MASE, MAE"]
A -->|clustering| K["silhouette without labels,<br/>ARI with labels"]
Quick lookup
Section titled “Quick lookup”| I want to… | Use… | scoring= string |
|---|---|---|
| the average error in the target’s units | mean_absolute_error |
"neg_mean_absolute_error" |
| punish big misses more | root_mean_squared_error |
"neg_root_mean_squared_error" |
| the share of variance explained | r2_score |
"r2" |
| a percentage error (y never near 0) | mean_absolute_percentage_error |
"neg_mean_absolute_percentage_error" |
| errors on a log scale (prices, counts) | root_mean_squared_log_error |
"neg_root_mean_squared_log_error" |
| errors robust to a few outliers | median_absolute_error |
"neg_median_absolute_error" |
| an error for an under/over-forecast trade-off | mean_pinball_loss(y, q_pred, alpha=0.9) |
make_scorer(..., greater_is_better=False) |
| the share of correct labels (balanced classes) | accuracy_score |
"accuracy" |
| accuracy that ignores class sizes | balanced_accuracy_score |
"balanced_accuracy" |
| how many flagged cases are real | precision_score |
"precision" |
| how many real cases were caught | recall_score |
"recall" |
| one number for precision and recall | f1_score, fbeta_score(beta=2) |
"f1" |
| one balanced number for all four cells | matthews_corrcoef |
"matthews_corrcoef" |
| ranking quality, balanced classes | roc_auc_score(y, proba) |
"roc_auc" |
| ranking quality, rare positives | average_precision_score(y, proba) |
"average_precision" |
| the quality of probabilities | log_loss, brier_score_loss |
"neg_log_loss", "neg_brier_score" |
| check calibration by eye | CalibrationDisplay.from_predictions(y, proba) |
|
| the confusion matrix | confusion_matrix(y, pred) |
|
| all per-class metrics | classification_report(y, pred) |
|
| macro F1 for multiclass | f1_score(y, pred, average="macro") |
"f1_macro" |
| precision in the top k | sort by score, mean of the top k labels | a custom function |
| ranking with graded relevance | ndcg_score |
|
| the best threshold for a metric or a cost | TunedThresholdClassifierCV(model, scoring=...) |
|
| a forecast error that is scale-free | MASE: MAE ÷ seasonal naive MAE | a custom function |
| cluster quality without labels | silhouette_score, davies_bouldin_score |
|
| agreement with known groups | adjusted_rand_score |
|
| a metric for model selection | cross_val_score(model, X, y, scoring="...") |
|
| list every scoring string | sklearn.metrics.get_scorer_names() |
Regression metrics
Section titled “Regression metrics”| Metric | Formula | Function | Units | Misleads when |
|---|---|---|---|---|
| MAE | mean_absolute_error |
target | a few big misses matter much more than many small ones | |
| RMSE | root_mean_squared_error |
target | a few outliers dominate the score | |
| R² | r2_score |
none | you compare different test sets or target scales; a high R² still allows large errors | |
| MAPE | mean_absolute_percentage_error |
fraction | some y are near 0; it favors under-forecasts | |
| sMAPE | by hand | fraction (0–2) | both y and the forecast are near 0 | |
| WAPE | by hand | fraction | the total is dominated by a few big items | |
| RMSLE | RMSE of | root_mean_squared_log_error |
log ratio | y can be negative |
| Median AE | median_absolute_error |
target | big misses matter: it ignores them | |
| Pinball loss | asymmetric absolute error at quantile α | mean_pinball_loss |
target | you need a point forecast, not a quantile |
MAE is minimized by predicting the median; RMSE by predicting the mean. Choose the one that matches the number you want to predict.
import numpy as npfrom sklearn.metrics import ( mean_absolute_error, mean_absolute_percentage_error, root_mean_squared_error,)
y_true = np.array([120, 95, 140, 110, 3]) # the last item sells very littlecases = { "small misses": np.array([115, 100, 150, 108, 9]), "one big miss": np.array([115, 100, 150, 50, 3]),}for name, y_pred in cases.items(): print(f"{name:<13} MAE {mean_absolute_error(y_true, y_pred):5.1f} " f"RMSE {root_mean_squared_error(y_true, y_pred):5.1f} " f"MAPE {mean_absolute_percentage_error(y_true, y_pred):6.1%}")small misses MAE 5.6 RMSE 6.2 MAPE 43.7%one big miss MAE 16.0 RMSE 27.4 MAPE 14.2%In the first case, a 6-unit miss on the item that sells 3 makes MAPE 44%. In the second case, one 60-unit miss makes RMSE 1.7 times the MAE, while MAPE looks fine.
Classification metrics
Section titled “Classification metrics”| Metric | Formula | Function | Misleads when |
|---|---|---|---|
| Accuracy | accuracy_score |
classes are imbalanced: “always no” scores high | |
| Precision | precision_score |
read alone: flag one sure case and it is 1.0 | |
| Recall (sensitivity, TPR) | recall_score |
read alone: flag everything and it is 1.0 | |
| Specificity (TNR) | recall_score(y, pred, pos_label=0) |
positives are what matter | |
| F1 | f1_score |
FP and FN costs differ; true negatives are ignored | |
| F-beta | fbeta_score(beta=2) |
β is chosen without a cost argument | |
| Balanced accuracy | mean recall per class | balanced_accuracy_score |
one class matters far more |
| MCC | correlation of labels and predictions | matthews_corrcoef |
stakeholders need an intuitive number |
| ROC-AUC | P(score of a random positive > a random negative) | roc_auc_score |
positives are rare: many false positives still give a high AUC |
| Average precision (PR-AUC) | area under the precision–recall curve | average_precision_score |
compared across data with different positive rates |
| Log loss | log_loss |
a few confident mistakes blow it up | |
| Brier score | brier_score_loss |
positives are very rare (it stays small anyway) | |
| Precision at k | share of positives in the top k scores | by hand | k does not match the real capacity |
ROC-AUC and average precision need scores (predict_proba(X)[:, 1] or decision_function), never 0/1 labels. Threshold metrics (precision, recall, F1) depend on the threshold; predict uses 0.5.
The accuracy trap
Section titled “The accuracy trap”from sklearn.datasets import make_classificationfrom sklearn.dummy import DummyClassifierfrom sklearn.linear_model import LogisticRegressionfrom sklearn.metrics import ( accuracy_score, average_precision_score, balanced_accuracy_score, recall_score, roc_auc_score,)from sklearn.model_selection import train_test_split
X, y = make_classification(n_samples=4000, n_features=10, n_informative=4, weights=[0.95], flip_y=0.01, class_sep=0.8, random_state=42)X_tr, X_te, y_tr, y_te = train_test_split(X, y, test_size=0.5, stratify=y, random_state=42)print(f"positive share {y_te.mean():.3f}")models = {"always 0": DummyClassifier(), "logistic": LogisticRegression()}for name, model in models.items(): model.fit(X_tr, y_tr) pred, proba = model.predict(X_te), model.predict_proba(X_te)[:, 1] print(f"{name:<9} acc {accuracy_score(y_te, pred):.3f}" f" bal-acc {balanced_accuracy_score(y_te, pred):.3f}" f" recall {recall_score(y_te, pred, zero_division=0):.3f}" f" AP {average_precision_score(y_te, proba):.3f}" f" AUC {roc_auc_score(y_te, proba):.3f}")positive share 0.053always 0 acc 0.947 bal-acc 0.500 recall 0.000 AP 0.053 AUC 0.500logistic acc 0.949 bal-acc 0.523 recall 0.047 AP 0.307 AUC 0.708Both models reach 95% accuracy, and at the default threshold of 0.5 the logistic model catches almost no positives. The ranking metrics show the difference: AP rises from the positive share (0.053) to 0.307. The model is useful, but only with a lower threshold.
Choose the threshold from costs
Section titled “Choose the threshold from costs”Suppose every flagged customer gets a retention offer that costs 10, and the offer keeps a churner who would otherwise cost 100. A flagged row costs 10 whether it is a true or a false positive; a missed churner costs 100. Flag a customer when the expected saving beats the offer: . The break-even threshold for calibrated probabilities is :
for threshold in [0.5, 0.3, 0.2, 0.1, 0.05]: flag = proba >= threshold fp = int(np.sum(flag & (y_te == 0))) fn = int(np.sum(~flag & (y_te == 1))) print(f"threshold {threshold:<4} flagged {flag.sum():>4} FP {fp:>4} FN {fn:>3}" f" cost {10 * flag.sum() + 100 * fn:>6,}") # offers + lost churnersthreshold 0.5 flagged 5 FP 0 FN 102 cost 10,250threshold 0.3 flagged 18 FP 4 FN 93 cost 9,480threshold 0.2 flagged 40 FP 19 FN 86 cost 9,000threshold 0.1 flagged 198 FP 150 FN 59 cost 7,880threshold 0.05 flagged 767 FP 695 FN 35 cost 11,170The cost is lowest near the break-even threshold. In practice, tune it with TunedThresholdClassifierCV(model, scoring=make_scorer(profit)) on training data, never on the test set.
Precision at a fixed capacity
Section titled “Precision at a fixed capacity”When the team can call only k customers, judge the model by the share of positives among its top k scores:
order = np.argsort(-proba, kind="stable") # highest scores firstfor k in [50, 100, 200]: print(f"precision at {k:>3}: {y_te[order[:k]].mean():.2f} " f"(random: {y_te.mean():.2f})")precision at 50: 0.48 (random: 0.05)precision at 100: 0.34 (random: 0.05)precision at 200: 0.24 (random: 0.05)Multiclass averages
Section titled “Multiclass averages”from sklearn.metrics import f1_score
y_true_mc = ["A"] * 8 + ["B", "C"]y_pred_mc = ["A"] * 10 # always predicts the majority classfor avg in ["micro", "macro", "weighted"]: score = f1_score(y_true_mc, y_pred_mc, average=avg, zero_division=0) print(f"{avg:<8} F1 {score:.3f}")micro F1 0.800macro F1 0.296weighted F1 0.711| Average | How | Use when |
|---|---|---|
micro |
pool all TP, FP, FN; equals accuracy for single-label data | overall correctness |
macro |
mean of the per-class scores | every class matters equally (rare classes too) |
weighted |
per-class scores weighted by class size | reporting; it hides weak rare classes |
Business goal → metric
Section titled “Business goal → metric”| Task | Business goal | Metric | Why |
|---|---|---|---|
| churn | call the 500 riskiest customers each month | precision at 500, lift | the capacity is fixed |
| churn | offers cost 10, a lost customer 100 | expected cost at a tuned threshold | the costs are known |
| fraud | review 1% of transactions, catch as much as possible | recall at a 1% alert rate | analysts are the bottleneck |
| fraud | compare models before a threshold exists | average precision | rare positives |
| medical screening | miss almost no cases | recall at a specificity floor (or the reverse) | a FN is far worse than a FP |
| spam filter | never lose a real email | recall at a fixed low FPR (for example 0.1%), or at a precision floor | a FP (a real email in spam) is far worse |
| credit risk, insurance | prices depend on the probability | log loss, Brier, calibration curve | the probabilities feed money |
| response targeting | rank who is most likely to buy | ROC-AUC, gains curve | only the order of the response matters |
| marketing uplift | rank who changes behavior because of the offer | Qini curve, uplift curve (area under it) on a randomized treatment/control holdout | a response model ranks “sure things” first: high AUC, zero uplift |
| house prices | be within 10% of the sale price | share within ±10%, MAPE | the error is judged relative to price |
| demand forecast | under-stocking costs more than over-stocking | pinball loss at α = 0.9 | an asymmetric cost |
| demand forecast | compare series of different sizes | MASE, WAPE | scale-free |
| revenue forecast | totals in money matter | MAE, WAPE | the errors add up in money |
| search, recommendations | the best items first | NDCG, precision at k | graded relevance, top positions |
| customer segments | groups that are distinct and usable | silhouette plus business review | there are no labels |
Forecast and clustering metrics
Section titled “Forecast and clustering metrics”| Metric | Formula or function | Note |
|---|---|---|
| MAE, RMSE | as above, on the backtest windows | report per horizon (1 day, 7 days, 28 days) |
| MASE | MAE ÷ in-sample seasonal naive MAE | below 1 beats the seasonal naive forecast; works with zeros |
| sMAPE | see the table above | 0 to 200% |
| interval coverage | share of actuals inside the 95% interval | should be close to 95% |
silhouette_score(X, labels) |
−1 to 1 | separation; about 0.2 is normal for behavior data |
davies_bouldin_score(X, labels) |
≥ 0, lower is better | compactness vs separation |
adjusted_rand_score(a, b) |
about 0 (random) to 1 | agreement with labels or another clustering; ignores label names |
Gotchas
Section titled “Gotchas”| Trap | Symptom | Fix |
|---|---|---|
| accuracy on imbalanced classes | 95% for a model that predicts “no” | balanced accuracy, AP, recall at a fixed precision |
| ROC-AUC or AP on 0/1 predictions | a much lower, odd score | pass predict_proba(X)[:, 1] |
metric(y_pred, y_true) |
wrong values (R², precision and recall are not symmetric) | metric(y_true, y_pred) |
scoring="neg_..." |
negative numbers; “max” means the smallest error | flip the sign before you report |
mean_squared_error(..., squared=False) |
TypeError (removed in scikit-learn 1.6) |
root_mean_squared_error |
| MAPE with y near 0 | a huge percentage from tiny items | WAPE, MASE or MAE |
mean_absolute_percentage_error read as a percent |
0.12 shown as “0.12%” | it is a fraction: format with :.1% |
| R² compared across test sets | a “better” model on an easier split | compare on the same split; report MAE too |
| a log-target model scored on the log scale | errors look tiny | back-transform before scoring: np.expm1 after np.log1p (np.exp after np.log), or TransformedTargetRegressor(func=np.log1p, inverse_func=np.expm1) |
| F1 when costs are known | the wrong threshold | expected cost or profit |
| threshold tuned on the test set | an optimistic score | TunedThresholdClassifierCV on training data |
| precision with no positive predictions | UndefinedMetricWarning |
zero_division=0, and check the threshold |
| class weights or resampling | probabilities shift upward | judge log loss and Brier after calibration |
weighted average in multiclass |
weak rare classes are hidden | macro, plus the per-class report |
| silhouette as the only cluster check | “best k” that nobody can use | profile the clusters; check stability with ARI |
| one score without spread | a lucky split looks like progress | CV mean ± std, or a paired comparison |
Learn more
Section titled “Learn more”- Module 35: regression and its cheat sheet
- Module 36: classification and its cheat sheet
- Module 37: model evaluation and tuning and its cheat sheet
- Module 40: time series and its cheat sheet for MASE and backtests
- Decision guides: which CV strategy and which algorithm