A metric turns predictions into one number that you can compare. This page gives the formula, the scikit-learn function and the scoring= name of each common metric, for regression, classification, probabilities, ranking and forecasts, and then shows how to choose a decision threshold. The examples use data/houses.csv, data/customers.csv and data/web_traffic.csv. The blocks share one session:
from sklearn.compose import make_column_transformer
from sklearn.ensemble import HistGradientBoostingRegressor
from sklearn.linear_model import LogisticRegression
from sklearn.model_selection import train_test_split
from sklearn.pipeline import make_pipeline
from sklearn.preprocessing import OneHotEncoder, StandardScaler
from threadpoolctl import threadpool_limits
threadpool_limits( limits = 1 ) # one thread: faster on small data, same scores
houses = pd.read_csv( "data/houses.csv" ).astype({ "neighborhood" : "category" })
Xh = houses.drop( columns = [ "house_id" , "sold_date" , "price" ])
Xh_tr, Xh_te, yh_tr, yh_te = train_test_split(
Xh, houses[ "price" ], test_size = 0.25 , random_state = 42
reg = HistGradientBoostingRegressor( random_state = 42 ).fit(Xh_tr, yh_tr)
pred_h = reg.predict(Xh_te) # USD
customers = pd.read_csv( "data/customers.csv" )
Xc = customers[[ "tenure_months" , "monthly_charges" , "support_tickets" , "contract" ]]
Xc_tr, Xc_te, yc_tr, yc_te = train_test_split(
Xc, customers[ "churned" ], test_size = 0.25 , stratify = customers[ "churned" ],
prep = make_column_transformer(
(OneHotEncoder( handle_unknown = "ignore" ), [ "contract" ]), remainder = StandardScaler()
clf = make_pipeline(prep, LogisticRegression( max_iter = 1000 )).fit(Xc_tr, yc_tr)
proba = clf.predict_proba(Xc_te)[:, 1 ] # P(churn)
pred_c = clf.predict(Xc_te) # 1 when P(churn) > 0.5
print ( f "churn rate { yc_te.mean() :.3f } , test rows {len (yc_te) } " )
churn rate 0.193, test rows 1250
I want to…
Use…
scoring= name
the typical error in target units
mean_absolute_error(y, p)
"neg_mean_absolute_error"
an error that punishes big misses
root_mean_squared_error(y, p)
"neg_root_mean_squared_error"
the share of variance explained
r2_score(y, p)
"r2"
a relative error
mean_absolute_percentage_error(y, p)
"neg_mean_absolute_percentage_error"
an error robust to outliers
median_absolute_error(y, p)
"neg_median_absolute_error"
errors in ratios (log scale)
root_mean_squared_log_error(y, p)
"neg_root_mean_squared_log_error"
the quality of a quantile forecast
mean_pinball_loss(y, p, alpha=0.9)
make_scorer(..., greater_is_better=False)
count each kind of error
confusion_matrix(y, pred).ravel()
(TN, FP, FN, TP)
precision, recall, F1 per class
classification_report(y, pred, digits=3)
the share of flagged rows that are right
precision_score(y, pred)
"precision"
the share of positives caught
recall_score(y, pred)
"recall"
one number for precision and recall
f1_score(y, pred), fbeta_score(y, pred, beta=2)
"f1"
accuracy that respects rare classes
balanced_accuracy_score(y, pred)
"balanced_accuracy"
one balanced number from the confusion matrix
matthews_corrcoef(y, pred)
"matthews_corrcoef"
a ranking quality, any threshold
roc_auc_score(y, proba)
"roc_auc"
ranking quality with rare positives
average_precision_score(y, proba)
"average_precision"
the quality of probabilities
log_loss(y, proba), brier_score_loss(y, proba)
"neg_log_loss", "neg_brier_score"
probabilities vs observed rates
calibration_curve(y, proba, n_bins=10)
multiclass ROC-AUC
roc_auc_score(y, P, multi_class="ovr")
"roc_auc_ovr"
a macro average over classes
f1_score(y, pred, average="macro")
"f1_macro"
precision in the top k
sort by score, take k, average y
custom
a ranking metric with graded relevance
ndcg_score(y_rel, scores, k=10)
every point of the precision–recall trade-off
precision_recall_curve(y, proba)
a fixed threshold in a model
FixedThresholdClassifier(model, threshold=0.3)
a threshold chosen by CV
TunedThresholdClassifierCV(model, scoring="f1")
a scale-free forecast error
MASE: MAE ÷ in-sample seasonal naive MAE
custom
list every scorer name
sklearn.metrics.get_scorer_names()
a scorer from my own function
make_scorer(func, greater_is_better=False)
Every metric takes (y_true, y_pred) in that order.
Metric
Formula
Function
Unit
Misleads when
MAE
1 n ∑ ∣ y − y ^ ∣ \frac{1}{n}\sum \lvert y - \hat{y} \rvert n 1 ∑ ∣ y − y ^ ∣
mean_absolute_error
target
large misses matter more than small ones
MSE
1 n ∑ ( y − y ^ ) 2 \frac{1}{n}\sum (y - \hat{y})^2 n 1 ∑ ( y − y ^ ) 2
mean_squared_error
target²
always hard to read
RMSE
MSE \sqrt{\text{MSE}} MSE
root_mean_squared_error
target
a few outliers dominate
R²
1 − ∑ ( y − y ^ ) 2 ∑ ( y − y ˉ ) 2 1 - \frac{\sum (y - \hat{y})^2}{\sum (y - \bar{y})^2} 1 − ∑ ( y − y ˉ ) 2 ∑ ( y − y ^ ) 2
r2_score
none, ≤ 1
comparing test sets with different spreads
MAPE
1 n ∑ ∣ y − y ^ y ∣ \frac{1}{n}\sum \left\lvert \frac{y - \hat{y}}{y} \right\rvert n 1 ∑ y y − y ^
mean_absolute_percentage_error
fraction
y y y near 0; favors under-forecasts
MedAE
median ∣ y − y ^ ∣ \operatorname{median} \lvert y - \hat{y} \rvert median ∣ y − y ^ ∣
median_absolute_error
target
hides the tail
max error
max ∣ y − y ^ ∣ \max \lvert y - \hat{y} \rvert max ∣ y − y ^ ∣
max_error
target
one row decides
RMSLE
1 n ∑ ( log ( 1 + y ) − log ( 1 + y ^ ) ) 2 \sqrt{\frac{1}{n}\sum (\log(1+y) - \log(1+\hat{y}))^2} n 1 ∑ ( log ( 1 + y ) − log ( 1 + y ^ ) ) 2
root_mean_squared_log_error
log ratio
needs y , y ^ > − 1 y, \hat{y} > -1 y , y ^ > − 1
pinball loss
1 n ∑ max ( α ( y − y ^ ) , ( α − 1 ) ( y − y ^ ) ) \frac{1}{n}\sum \max(\alpha(y - \hat{y}),\,(\alpha - 1)(y - \hat{y})) n 1 ∑ max ( α ( y − y ^ ) , ( α − 1 ) ( y − y ^ ))
mean_pinball_loss(alpha=)
target
used for a mean forecast
Poisson deviance
2 n ∑ ( y log y y ^ − y + y ^ ) \frac{2}{n}\sum \left(y \log\frac{y}{\hat{y}} - y + \hat{y}\right) n 2 ∑ ( y log y ^ y − y + y ^ )
mean_poisson_deviance
none
y ^ ≤ 0 \hat{y} \le 0 y ^ ≤ 0
D² (absolute error)
1 − ∑ ∣ y − y ^ ∣ ∑ ∣ y − median ( y ) ∣ 1 - \frac{\sum \lvert y - \hat{y} \rvert}{\sum \lvert y - \operatorname{median}(y) \rvert} 1 − ∑ ∣ y − median ( y )∣ ∑ ∣ y − y ^ ∣
d2_absolute_error_score
none, ≤ 1
as R², for MAE
from sklearn.metrics import (
mean_absolute_percentage_error,
root_mean_squared_log_error,
print ( f "MAE { mean_absolute_error(yh_te, pred_h) :>9,.0f } " ) # y_true first
print ( f "RMSE { root_mean_squared_error(yh_te, pred_h) :>9,.0f } " )
print ( f "MedAE { median_absolute_error(yh_te, pred_h) :>9,.0f } " )
print ( f "max { max_error(yh_te, pred_h) :>9,.0f } " )
print ( f "R² { r2_score(yh_te, pred_h) :>9.3f } " )
print ( f "MAPE { mean_absolute_percentage_error(yh_te, pred_h) :>9.1% } " ) # a fraction
print ( f "RMSLE { root_mean_squared_log_error(yh_te, pred_h) :>9.3f } " )
RMSE ≥ MAE always. A large gap means a few big misses: inspect the worst rows.
actual 0 (neg) TN FP specificity = TN / (TN + FP)
actual 1 (pos) FN TP recall = TP / (TP + FN)
precision = TP / (TP + FP)
Metric
Formula
Function
Range
Use when
accuracy
T P + T N n \frac{TP + TN}{n} n T P + T N
accuracy_score
0–1
balanced classes, equal costs
balanced accuracy
mean recall over classes
balanced_accuracy_score
1/K random (0.5 for binary) – 1
imbalanced classes
precision
T P T P + F P \frac{TP}{TP + FP} T P + F P T P
precision_score
0–1
false alarms are expensive
recall (sensitivity, TPR)
T P T P + F N \frac{TP}{TP + FN} T P + F N T P
recall_score
0–1
misses are expensive
specificity (TNR)
T N T N + F P \frac{TN}{TN + FP} T N + F P T N
recall_score(y, pred, pos_label=0)
0–1
screening tests
F1
2 P R P + R \frac{2PR}{P + R} P + R 2 P R
f1_score
0–1
one number for P and R
F-beta
( 1 + β 2 ) P R β 2 P + R \frac{(1 + \beta^2) P R}{\beta^2 P + R} β 2 P + R ( 1 + β 2 ) P R
fbeta_score(beta=2)
0–1
β > 1 \beta > 1 β > 1 weighs recall more
MCC
T P ⋅ T N − F P ⋅ F N ( T P + F P ) ( T P + F N ) ( T N + F P ) ( T N + F N ) \frac{TP \cdot TN - FP \cdot FN}{\sqrt{(TP+FP)(TP+FN)(TN+FP)(TN+FN)}} ( T P + F P ) ( T P + F N ) ( T N + F P ) ( T N + F N ) T P ⋅ T N − F P ⋅ F N
matthews_corrcoef
−1 to 1
one honest number for imbalance
Cohen’s kappa
p o − p e 1 − p e \frac{p_o - p_e}{1 - p_e} 1 − p e p o − p e
cohen_kappa_score
−1 to 1
agreement beyond chance (annotators)
from sklearn.metrics import (
tn, fp, fn, tp = confusion_matrix(yc_te, pred_c).ravel() # true labels first
print ( f "TN { tn } FP { fp } FN { fn } TP { tp } " )
print ( f "accuracy { accuracy_score(yc_te, pred_c) :.3f } "
f "balanced { balanced_accuracy_score(yc_te, pred_c) :.3f } "
f "MCC { matthews_corrcoef(yc_te, pred_c) :.3f } " )
print ( f "precision { precision_score(yc_te, pred_c) :.3f } "
f "recall { recall_score(yc_te, pred_c) :.3f } "
f "F1 { f1_score(yc_te, pred_c) :.3f } F2 { fbeta_score(yc_te, pred_c, beta = 2 ) :.3f } " )
print (classification_report(yc_te, pred_c, digits = 3 , target_names = [ "stay" , "churn" ]))
TN 969 FP 40 FN 177 TP 64
accuracy 0.826 balanced 0.613 MCC 0.323
precision 0.615 recall 0.266 F1 0.371 F2 0.300
precision recall f1-score support
stay 0.846 0.960 0.899 1009
churn 0.615 0.266 0.371 241
macro avg 0.730 0.613 0.635 1250
weighted avg 0.801 0.826 0.797 1250
High accuracy with low recall: the model mostly predicts “stay”, like the majority baseline (accuracy 0.807 here).
average=
Computes
Use when
"binary" (default)
the metric for pos_label=1 only
two classes
"macro"
plain mean over classes
every class matters equally
"weighted"
mean weighted by class size
large classes matter more
"micro"
pools TP, FP, FN over classes
equals accuracy for single-label multiclass
None
one value per class
the honest view
Metric
Formula
Function
Best
Notes
log loss
− 1 n ∑ [ y log p + ( 1 − y ) log ( 1 − p ) ] -\frac{1}{n}\sum [y \log p + (1 - y)\log(1 - p)] − n 1 ∑ [ y log p + ( 1 − y ) log ( 1 − p )]
log_loss
0
punishes confident mistakes hard
Brier score
1 n ∑ ( p − y ) 2 \frac{1}{n}\sum (p - y)^2 n 1 ∑ ( p − y ) 2
brier_score_loss
0
MSE of the probabilities
D² log loss
1 − log loss log loss of the base rate 1 - \frac{\text{log loss}}{\text{log loss of the base rate}} 1 − log loss of the base rate log loss
d2_log_loss_score
1
like R² for probabilities
calibration curve
observed rate per bin of p p p
calibration_curve(y, p, n_bins, strategy="quantile")
the diagonal
plot: CalibrationDisplay
from sklearn.calibration import calibration_curve
from sklearn.metrics import brier_score_loss, d2_log_loss_score, log_loss
base = np.full( len (yc_te), yc_tr.mean()) # always predict the training churn rate
for name, p in [( "model" , proba), ( "base rate" , base)]:
print ( f " { name :<9 } log loss { log_loss(yc_te, p) :.3f } "
f "Brier { brier_score_loss(yc_te, p) :.3f } " )
print ( f "D² log loss { d2_log_loss_score(yc_te, proba) :.3f } " )
observed, predicted = calibration_curve(yc_te, proba, n_bins = 5 , strategy = "quantile" )
print ( "predicted" , predicted.round( 2 ), " \n observed " , observed.round( 2 ))
model log loss 0.396 Brier 0.124
base rate log loss 0.490 Brier 0.156
predicted [0.02 0.07 0.16 0.27 0.49]
observed [0.02 0.07 0.15 0.22 0.5 ]
Metric
Meaning
Function
Random model
ROC-AUC
P(a random positive scores above a random negative)
roc_auc_score(y, score)
0.5
average precision (PR-AUC)
mean precision over the recall levels
average_precision_score(y, score)
the positive share
precision at k
positives among the top k
y[np.argsort(-score)[:k]].mean()
the positive share
lift at k
precision at k ÷ positive share
1
top-k accuracy
true class among the k highest scores
top_k_accuracy_score(y, P, k=3)
k / classes
NDCG at k
discounted gain of graded relevance
ndcg_score(y_rel, scores, k=10)
depends
from sklearn.metrics import average_precision_score, roc_auc_score
print ( f "ROC-AUC { roc_auc_score(y_arr, proba) :.3f } " # scores, never labels
f "AP { average_precision_score(y_arr, proba) :.3f } base rate { y_arr.mean() :.3f } " )
order = np.argsort( - proba, kind = "stable" ) # highest risk first
prec_k = y_arr[order[:k]].mean()
print ( f "top { k :>3 } : precision { prec_k :.3f } , lift { prec_k / y_arr.mean() :.2f } " )
ROC-AUC 0.793 AP 0.533 base rate 0.193
top 50: precision 0.780, lift 4.05
top 125: precision 0.592, lift 3.07
top 250: precision 0.504, lift 2.61
Metric
Formula
Notes
MAE, RMSE
as for regression
in the units of the series
MAPE
100 n ∑ ∣ y t − y ^ t y t ∣ \frac{100}{n}\sum \left\lvert \frac{y_t - \hat{y}_t}{y_t} \right\rvert n 100 ∑ y t y t − y ^ t
breaks at 0; mean_absolute_percentage_error returns a fraction
sMAPE
100 n ∑ 2 ∣ y t − y ^ t ∣ ∣ y t ∣ + ∣ y ^ t ∣ \frac{100}{n}\sum \frac{2 \lvert y_t - \hat{y}_t \rvert}{\lvert y_t \rvert + \lvert \hat{y}_t \rvert} n 100 ∑ ∣ y t ∣ + ∣ y ^ t ∣ 2 ∣ y t − y ^ t ∣
0–200 (some tools report a fraction, 0–2); not symmetric in practice
WAPE
∑ ∣ y t − y ^ t ∣ ∑ ∣ y t ∣ \frac{\sum \lvert y_t - \hat{y}_t \rvert}{\sum \lvert y_t \rvert} ∑ ∣ y t ∣ ∑ ∣ y t − y ^ t ∣
total error ÷ total volume; robust to small values
MASE
MAE 1 T − m ∑ t = m + 1 T ∣ y t − y t − m ∣ \frac{\text{MAE}}{\frac{1}{T - m}\sum_{t=m+1}^{T} \lvert y_t - y_{t-m} \rvert} T − m 1 ∑ t = m + 1 T ∣ y t − y t − m ∣ MAE
below 1 beats the in-sample seasonal naive forecast
pinball loss
as for regression, at each quantile
quantile forecasts
interval coverage
share of y t y_t y t inside the interval
95% intervals should cover about 95%
sales = pd.read_csv( "data/sales.csv" , parse_dates = [ "order_date" ])
units = sales.groupby( "order_date" )[ "quantity" ].sum().asfreq( "D" , fill_value = 0 )
train, test = units.iloc[: - 28 ], units.iloc[ - 28 :] # the last 4 weeks are the test
forecast = np.tile(train.iloc[ - 7 :].to_numpy(), 4 ) # seasonal naive: repeat last week
err = test.to_numpy() - forecast
scale = np.mean(np.abs(hist[ 7 :] - hist[: - 7 ])) # in-sample seasonal naive MAE
mae = np.mean(np.abs(err))
print ( f "MAE { mae :,.1f } units per day" )
print ( f "MAPE { np.mean(np.abs(err / test.to_numpy())) :.1% } " )
print ( f "sMAPE { np.mean( 2 * np.abs(err) / (np.abs(test) + np.abs(forecast))) :.1% } " )
print ( f "WAPE { np.abs(err).sum() / test.abs().sum() :.1% } " )
print ( f "MASE { mae / scale :.2f } " )
The last training week holds the Black Friday peak (November 29 to December 2), so the seasonal naive forecast repeats that peak four times: MASE 4.51 means 4.5 times the in-sample naive error. MAPE is the largest of the percentages because low days, such as 16 units on December 25, divide by small numbers. The time-series page compares these metrics across several baselines and a SARIMA model.
cross_val_score, cross_validate and every search take scoring=: a name, a callable scorer(estimator, X, y), or a list or dict of them. Higher is always better, so errors come negated.
Task
Names
regression
"r2", "neg_mean_absolute_error", "neg_root_mean_squared_error", "neg_mean_absolute_percentage_error", "neg_median_absolute_error", "neg_root_mean_squared_log_error", "neg_mean_poisson_deviance", "d2_absolute_error_score"
binary labels
"accuracy", "balanced_accuracy", "precision", "recall", "f1", "matthews_corrcoef"
binary scores
"roc_auc", "average_precision", "neg_log_loss", "neg_brier_score"
multiclass
"f1_macro", "f1_weighted", "precision_macro", "recall_macro", "roc_auc_ovr", "roc_auc_ovo", "neg_log_loss"
clustering (with true labels)
"adjusted_rand_score", "adjusted_mutual_info_score"
from sklearn.metrics import fbeta_score, get_scorer_names, make_scorer
from sklearn.model_selection import StratifiedKFold, cross_validate
cv = StratifiedKFold( n_splits = 5 , shuffle = True , random_state = 42 )
f2 = make_scorer(fbeta_score, beta = 2 ) # extra arguments go to the metric
res = cross_validate(clf, Xc_tr, yc_tr, cv = cv,
scoring = { "auc" : "roc_auc" , "f2" : f2, "ll" : "neg_log_loss" })
for key in [ "test_auc" , "test_f2" , "test_ll" ]:
print ( f " { key :<8 } { res[key].mean() :.3f } " ) # neg_log_loss is negative
print ( "neg_root_mean_squared_error" in get_scorer_names())
make_scorer argument
Meaning
greater_is_better=False
an error: the scorer negates it
response_method="predict" (default)
the metric gets labels
response_method="predict_proba"
the metric gets probabilities (positive column for binary)
response_method=("decision_function", "predict_proba")
the first method the model has
**kwargs
passed to the metric: beta=2, average="macro", pos_label=0
predict uses 0.5 for probabilities (0 for decision_function). The best threshold depends on the costs. Choose it on validation data or with cross-validation, never on the test set.
Goal
Rule
calibrated probabilities, cost c F P c_{FP} c F P per false alarm, c F N c_{FN} c F N per miss
flag when p > c F P c F P + c F N p > \frac{c_{FP}}{c_{FP} + c_{FN}} p > c F P + c F N c F P
a recall target
the highest threshold whose validation recall ≥ the target
a precision target
the lowest threshold whose validation precision ≥ the target
a fixed capacity of k actions
the top k scores
any score or cost function
TunedThresholdClassifierCV(model, scoring=...)
from sklearn.metrics import precision_recall_curve
from sklearn.model_selection import FixedThresholdClassifier, TunedThresholdClassifierCV
def profit (y_true, y_pred): # a kept customer is worth 200, an offer costs 40
tp = ((y_true == 1 ) & (y_pred == 1 )).sum()
return 200 * 0.3 * tp - 40 * y_pred.sum() # 30% of offered churners stay
tuned = TunedThresholdClassifierCV(clf, scoring = make_scorer(profit), cv = cv)
tuned.fit(Xc_tr, yc_tr) # threshold chosen by CV on the training rows
fixed = FixedThresholdClassifier(clf, threshold = 0.3 ).fit(Xc_tr, yc_tr)
print ( f "tuned threshold { tuned.best_threshold_ :.3f } " )
for name, model in [( "0.5" , clf), ( "0.3" , fixed), ( "tuned" , tuned)]:
pred = model.predict(Xc_te)
print ( f " { name :<5 } flagged { pred.sum() :>4 } recall { recall_score(yc_te, pred) :.3f } "
f " profit { profit(yc_te.to_numpy(), pred) :>8,.0f } " )
prec, rec, thr = precision_recall_curve(yc_tr, clf.predict_proba(Xc_tr)[:, 1 ])
print ( f "highest threshold with recall >= 0.8: { thr[rec[: - 1 ] >= 0.8 ].max() :.3f } " )
0.5 flagged 104 recall 0.266 profit -320
0.3 flagged 324 recall 0.593 profit -4,380
tuned flagged 47 recall 0.154 profit 340
highest threshold with recall >= 0.8: 0.178
An offer pays off when 60 p > 40 60p > 40 60 p > 40 , so the break-even probability is 40 / 60 = 0.667 40 / 60 = 0.667 40/60 = 0.667 ; cross-validation picks a threshold close to it. The last line uses training-set predictions only to show the API. In practice use out-of-fold predictions: cross_val_predict(clf, X, y, cv=cv, method="predict_proba").
Trap
Symptom
Fix
arguments swapped: metric(pred, y)
wrong R²; precision and recall exchanged
always (y_true, y_pred)
labels passed to roc_auc_score
AUC of one threshold, usually lower
pass predict_proba(X)[:, 1] or decision_function(X)
accuracy on imbalanced data
0.81 for “nobody churns”
balanced accuracy, recall, AP; print the baseline
neg_ scorer values
negative scores in reports
flip the sign
mean_squared_error(..., squared=False)
TypeError (removed in 1.6)
root_mean_squared_error
MAPE printed as 0.12
read as 0.12%
it is a fraction: format with :.1%
MAPE with zeros in y
huge or infinite values
MAE, WAPE or MASE
R² compared across test sets
a model “improves” on an easier split
compare on the same rows
precision with nothing flagged
UndefinedMetricWarning, value 0
zero_division=0 on purpose
pos_label
metrics for the wrong class (load_breast_cancer: 1 = benign)
recode, or pass pos_label=
predict_proba column order
the probability of the wrong class
it follows model.classes_
multiclass AUC from one column
ValueError
pass the full (n, K) matrix with multi_class="ovr"
a threshold tuned on the test set
an optimistic test score
TunedThresholdClassifierCV or a validation split
TunedThresholdClassifierCV(scoring="recall")
threshold near 0: everything flagged
tune on F1, F-beta or a cost
log_loss(y, pred) with labels
huge values
pass probabilities
macro vs weighted averages
weighted hides a weak rare class
report macro and the per-class table