A model with 94.6% accuracy that finds nothing
Accuracy, the fraction of correct predictions, is the first metric you compute and the first that deceives. If frauds, failures or diseases are rare, always saying "no problem" earns a very high score and is useless. The listing demonstrates it on 5000 transactions, 5% of which are fraudulent: a DummyClassifier that always answers "not fraud" is compared on three metrics. After overfitting and before the end-to-end pipeline, this is the step that decides whether the number you are looking at is worth anything. To recall the notion of classifier and the baseline, start again from the introduction.
from sklearn.datasets import make_classification
from sklearn.dummy import DummyClassifier
from sklearn.metrics import accuracy_score, balanced_accuracy_score, recall_score
from sklearn.model_selection import train_test_split
# 5% positive cases (for example fraudulent transactions), 95% negative
X, y = make_classification(n_samples=5000, n_features=10, n_informative=4, weights=[0.95], random_state=0)
X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.2, random_state=0, stratify=y)
sempre_no = DummyClassifier(strategy="most_frequent").fit(X_train, y_train)
pred = sempre_no.predict(X_test)
print(f"share of positives in the test set: {y_test.mean():.3f}")
print(f"accuracy of the model that always says 'no': {accuracy_score(y_test, pred):.3f}")
print(f"recall on positives: {recall_score(y_test, pred):.3f} balanced accuracy: {balanced_accuracy_score(y_test, pred):.3f}")
# Output:
# share of positives in the test set: 0.054
# accuracy of the model that always says 'no': 0.946
# recall on positives: 0.000 balanced accuracy: 0.500
The positives in the test set are 5.4% (the generation produces about 5%), and the model that does nothing has an accuracy of 0.946. Its recall on the positives is 0.000: it does not find a single fraud. The balanced accuracy, the mean of the recall of each class, is 0.500, the value of chance. This is the first rule for reading a metric: always compare it with what a trivial model would obtain, and choose metrics that do not let themselves be fooled by the most numerous class.
The confusion matrix and the three metrics derived from it
Every classification metric is derived from four numbers, which are all read with respect to a class that you call "positive". The true positives (TP) are the positive cases found; the false negatives (FN) are the positive cases missed; the false positives (FP) are false alarms; the true negatives (TN) are the negatives left alone. From here: the precision, TP / (TP + FP), answers "when the model raises the alarm, how often is it right?"; the recall, TP / (TP + FN), answers "of the true cases, how many did I find?"; the F1 is their harmonic mean, which stays low if either of the two is low, and therefore cannot be compensated.
In the listing I use the breast cancer dataset with a choice that many guides ignore: class 1 of the dataset is "benign" and 0 is "malignant". The case you do not want to miss is the malignant one, so I call it positive, with pos_label=0 and labels=[1, 0] in the confusion matrix. If I left the defaults, precision and recall would describe the ability to find benign tumors, which is not what matters. The metrics are computed by hand from the four numbers and compared with scikit-learn.
from sklearn.datasets import load_breast_cancer
from sklearn.linear_model import LogisticRegression
from sklearn.metrics import classification_report, confusion_matrix, f1_score, precision_score, recall_score
from sklearn.model_selection import train_test_split
from sklearn.pipeline import make_pipeline
from sklearn.preprocessing import StandardScaler
dati = load_breast_cancer()
# In the dataset 0 = malignant, 1 = benign. The case we do not want to miss is the malignant one: we call it "positive".
X_train, X_test, y_train, y_test = train_test_split(dati.data, dati.target, test_size=0.2, random_state=42)
modello = make_pipeline(StandardScaler(), LogisticRegression()).fit(X_train, y_train)
pred = modello.predict(X_test)
# With the classes in the order [0, 1] the matrix is [[TN, FP], [FN, TP]] with respect to class 1 (benign).
# To have the malignant as positive the roles are swapped: pos_label=0.
tn, fp, fn, tp = confusion_matrix(y_test, pred, labels=[1, 0]).ravel()
print(f"positive = malignant: TP={tp} FN={fn} FP={fp} TN={tn}")
precision = tp / (tp + fp)
recall = tp / (tp + fn)
f1 = 2 * precision * recall / (precision + recall)
print(f"by hand: precision {precision:.3f} recall {recall:.3f} F1 {f1:.3f}")
print(f"sklearn: precision {precision_score(y_test, pred, pos_label=0):.3f} recall {recall_score(y_test, pred, pos_label=0):.3f} F1 {f1_score(y_test, pred, pos_label=0):.3f}")
print(classification_report(y_test, pred, target_names=dati.target_names))
# Output:
# positive = malignant: TP=41 FN=2 FP=1 TN=70
# by hand: precision 0.976 recall 0.953 F1 0.965
# sklearn: precision 0.976 recall 0.953 F1 0.965
# precision recall f1-score support
#
# malignant 0.98 0.95 0.96 43
# benign 0.97 0.99 0.98 71
#
# accuracy 0.97 114
# macro avg 0.97 0.97 0.97 114
# weighted avg 0.97 0.97 0.97 114
The matrix says TP = 41, FN = 2, FP = 1, TN = 70: out of 43 malignant tumors the model found 41 and missed 2; it raised a single false alarm out of 71 benign ones. Precision 0.976 (41 correct alarms out of 42), recall 0.953 (41 malignant found out of 43), F1 0.965: the hand calculations and those of the library coincide. The classification_report repeats the numbers for both classes, and the "malignant" row is the one you have just computed. Note that the recall of the benign class is 0.99: the same matrix, read from the other side, tells another story. With only two errors out of 114 the picture is good, but the two metrics are not weighed in the same way: missing a malignant case costs much more than a false alarm, and the model, with the default threshold 0.5, does not know it.
The threshold is a decision, not a default
A probabilistic classifier does not return "yes" or "no", but a probability, and the class comes from the comparison with a threshold, 0.5 by default. Lowering the threshold triggers more alarms: recall tends to rise and precision to fall; raising it does the opposite. It is not a rigid mathematical rule, precision is not monotonic as the threshold varies, but it is the tendency you will almost always meet. The right threshold depends on the costs of the errors in your domain, and must be chosen without looking at the test set, otherwise the test set is no longer neutral. The listing respects this rule: it derives the probabilities on the training set with cross_val_predict (predictions made by models that did not see that sample), looks for the highest threshold that guarantees a recall of at least 0.98 on those predictions, and only at the end applies it to the test set.
import numpy as np
from sklearn.datasets import load_breast_cancer
from sklearn.linear_model import LogisticRegression
from sklearn.metrics import confusion_matrix
from sklearn.model_selection import cross_val_predict, train_test_split
from sklearn.pipeline import make_pipeline
from sklearn.preprocessing import StandardScaler
dati = load_breast_cancer()
X_train, X_test, y_train, y_test = train_test_split(dati.data, dati.target, test_size=0.2, random_state=42)
modello = make_pipeline(StandardScaler(), LogisticRegression())
# Positive = malignant (class 0): I work with the probability of being malignant
p_train = cross_val_predict(modello, X_train, y_train, cv=5, method="predict_proba")[:, 0] # "out-of-sample" predictions
maligno_train = (y_train == 0)
def recall_precision(p, vero_maligno, soglia):
pred_maligno = p >= soglia
tp = np.sum(pred_maligno & vero_maligno)
return tp / vero_maligno.sum(), tp / max(pred_maligno.sum(), 1)
# I pick the highest threshold that guarantees recall >= 0.98 on the TRAIN set (from the cross-validation predictions)
soglie = np.linspace(0.01, 0.99, 99)
candidate = [s for s in soglie if recall_precision(p_train, maligno_train, s)[0] >= 0.98]
scelta = max(candidate)
print(f"threshold chosen on the training set: {scelta:.2f}")
modello.fit(X_train, y_train)
p_test = modello.predict_proba(X_test)[:, 0]
maligno_test = (y_test == 0)
for soglia in (0.5, scelta):
r, p = recall_precision(p_test, maligno_test, soglia)
tn, fp, fn, tp = confusion_matrix(maligno_test, p_test >= soglia).ravel()
print(f"threshold {soglia:.2f}: recall {r:.3f} precision {p:.3f} -> malignant missed {fn}, benign flagged by mistake {fp}")
# Output:
# threshold chosen on the training set: 0.10
# threshold 0.50: recall 0.953 precision 0.976 -> malignant missed 2, benign flagged by mistake 1
# threshold 0.10: recall 0.977 precision 0.857 -> malignant missed 1, benign flagged by mistake 7
The search on the training set chooses a threshold of 0.10: a malignancy probability of 10% is enough to trigger the alarm. On the test set the recall goes from 0.953 to 0.977, that is the malignant cases missed drop from 2 to 1, but the precision falls from 0.976 to 0.857 and the benign cases flagged by mistake rise from 1 to 7. This is the trade-off in its concrete form: one fewer tumor missed at the price of six more false alarms. If a false alarm means one more biopsy and a missed tumor a late diagnosis, the price may be acceptable; if it means an invasive operation, perhaps not. With numbers this small, one case more or less moves the recall by more than two points, so the result must be read as an indication and not as a promise. scikit-learn has encapsulated this procedure in TunedThresholdClassifierCV, described in the evaluation guide, which chooses the threshold with cross-validation for you.
ROC-AUC and the precision-recall curve, when positives are rare
The ROC curve plots, for each threshold, the true positive rate (the recall) against the false positive rate; the AUC is the area under the curve. It has a meaning that can be computed in two lines: it is the probability that a randomly chosen positive receives a higher score than a randomly chosen negative. 0.5 is chance, 1.0 is perfect separation. The ROC does not depend on the threshold, and that is its merit. Its defect emerges with rare positives: the false positive rate is computed on the negatives, which are very many, so even hundreds of false alarms barely move it, while for whoever uses the model they are the majority of the alarms. The precision-recall curve and its area (average precision) look at precision, which does not have this problem; Saito and Rehmsmeier, in PLOS ONE, show this on imbalanced data.
The listing uses 5000 samples with 1% positives. First it computes the AUC with the pairwise definition and compares it with roc_auc_score; then it prints the average precision, the value of a random model (which coincides with the share of positives) and the maximum possible precision for three levels of recall.
import numpy as np
from sklearn.datasets import make_classification
from sklearn.linear_model import LogisticRegression
from sklearn.metrics import average_precision_score, precision_recall_curve, roc_auc_score
from sklearn.model_selection import train_test_split
X, y = make_classification(n_samples=20000, n_features=10, n_informative=4, n_clusters_per_class=1, weights=[0.99], flip_y=0, class_sep=1.0, random_state=3)
X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.25, random_state=3, stratify=y)
p = LogisticRegression(max_iter=1000).fit(X_train, y_train).predict_proba(X_test)[:, 1]
# The AUC is the probability that a randomly chosen positive gets a higher score than a randomly chosen negative
pos, neg = p[y_test == 1], p[y_test == 0]
confronti = (pos[:, None] > neg[None, :]).mean() + 0.5 * (pos[:, None] == neg[None, :]).mean()
print(f"positives in the test set: {int(y_test.sum())} out of {len(y_test)} ({y_test.mean():.3f})")
print(f"AUC by hand (positive-negative pairs): {confronti:.4f} roc_auc_score: {roc_auc_score(y_test, p):.4f}")
print(f"average precision (area under the precision-recall curve): {average_precision_score(y_test, p):.3f}")
print(f"average precision of a random model: {y_test.mean():.3f}")
# What a high AUC means when positives are rare: precision achievable at a given recall
precisione, richiamo, _ = precision_recall_curve(y_test, p)
for obiettivo in (0.5, 0.8, 0.95):
print(f"to find {obiettivo:.0%} of the positives the maximum precision is {precisione[richiamo >= obiettivo].max():.3f}")
# Output:
# positives in the test set: 50 out of 5000 (0.010)
# AUC by hand (positive-negative pairs): 0.9592 roc_auc_score: 0.9592
# average precision (area under the precision-recall curve): 0.679
# average precision of a random model: 0.010
# to find 50% of the positives the maximum precision is 0.897
# to find 80% of the positives the maximum precision is 0.353
# to find 95% of the positives the maximum precision is 0.035
The hand-computed AUC and the library's coincide to four decimals (0.9592), confirming the pairwise interpretation. An AUC of 0.96 would sound like an excellent result. The average precision is instead 0.679, against 0.010 for a random model. The last three lines are the ones that matter to whoever has to use the model: to find half of the frauds the maximum precision is 0.897, so almost every alarm is right; to find 80% it drops to 0.353, that is two alarms out of three are false; to find 95% it drops to 0.035, and only one alarm in twenty-nine is true. The AUC value does not change and says nothing of all this. With imbalanced classes always report the precision-recall curve too, and state at which recall you are interested in working.
Evaluating once is not enough: cross-validation and dispersion
A single train/test split gives one number; changing the seed you get another. Stratified cross-validation divides the data into k folds that keep the proportions of the classes, trains k times and provides k scores, from which mean and dispersion. The listing uses cross_validate with five metrics together on a random forest, and also prints minimum and maximum, because the standard deviation alone hides the width of the interval.
from sklearn.datasets import load_breast_cancer
from sklearn.ensemble import RandomForestClassifier
from sklearn.model_selection import StratifiedKFold, cross_validate
X, y = load_breast_cancer(return_X_y=True)
cv = StratifiedKFold(n_splits=5, shuffle=True, random_state=42)
metriche = ["accuracy", "precision", "recall", "f1", "roc_auc"]
r = cross_validate(RandomForestClassifier(n_estimators=100, random_state=42), X, y, cv=cv, scoring=metriche)
for m in metriche:
v = r["test_" + m]
print(f"{m:10s} mean {v.mean():.3f} standard deviation {v.std():.3f} min {v.min():.3f} max {v.max():.3f}")
# Output:
# accuracy mean 0.956 standard deviation 0.012 min 0.939 max 0.973
# precision mean 0.965 standard deviation 0.028 min 0.921 max 1.000
# recall mean 0.966 standard deviation 0.027 min 0.917 max 0.986
# f1 mean 0.965 standard deviation 0.010 min 0.952 max 0.979
# roc_auc mean 0.989 standard deviation 0.008 min 0.979 max 0.998
The mean accuracy is 0.956 with a standard deviation of 0.012, but behind a tidy number there is an oscillation: precision and recall range from 0.921 to 1.000 and from 0.917 to 0.986 depending on the fold, a dispersion more than double that of accuracy (0.028 and 0.027 against 0.012) because they are computed on a smaller subset of samples. The AUC, 0.989 on average with a dispersion of 0.008, is the most stable because it uses all the samples. When you compare two models, check that the difference between the means is larger than the dispersion: a difference of half a point with a standard deviation of 1.2 says nothing.
Choosing the metric, with a single question
The question is: "which error costs more, and how much?". If the false negative is the damage (missed diagnosis, unseen fraud) recall matters, with a low threshold and the cost of false alarms declared. If the false positive is the damage (important email ending up in spam, solvent customer rejected) precision matters. If you cannot rank them, F1 is a compromise, but remember that it gives the same weight to two errors that in reality do not have it. For imbalanced classes, balanced accuracy and average precision are more honest than accuracy. For regression MSE, MAE, RMSE and R² apply, already compared with a baseline in the article on regression; the MAE is less sensitive to extreme values, but this is a choice, not a rule, because sometimes you want precisely a large error to weigh a lot.
What you can do now
You can unmask an accuracy inflated by the majority class, build the confusion matrix carefully choosing which class is positive, and derive precision, recall and F1 by hand. You can choose the threshold on the training set and evaluate it once on the test set, and you can read a high AUC together with the precision-recall curve when positives are rare. You can report a mean with its dispersion. For the technique that separates a model that generalizes from one that memorizes, the next step is overfitting, underfitting and regularization.
Metrics intersect with preprocessing, where leakage inflates any score, and with recommendation systems, which use precision@K and NDCG@K.
Frequently asked questions
Why is accuracy not enough with imbalanced classes?
Because a model that always predicts the majority class gets a high accuracy without finding any rare case: in the example with 5% frauds it gets 0.946 with recall 0.000.
What is the difference between precision and recall?
Precision is the share of correct alarms, TP / (TP + FP); recall is the share of positive cases found, TP / (TP + FN). Lowering the classification threshold tends to raise recall and lower precision.
When is the precision-recall curve better than the ROC?
When positives are rare: the ROC AUC can stay high (0.96 in the example) while the precision at high recall is very low (0.035 at 95% recall).
How I checked the listings: I ran each one on its own on 2026-11-21 with Python 3.14.4, NumPy 2.3.5 and scikit-learn 1.8.0, and the decimal figures quoted in the text match the ones produced. With other library versions the last digits may change.
Sources
- scikit-learn User Guide: Metrics and scoring - definitions of precision, recall, F1, ROC-AUC, average precision, balanced accuracy and threshold tuning, consulted on 2026-11-12
- scikit-learn API: roc_auc_score - computation of the area under the ROC curve, consulted on 2026-11-12
- scikit-learn User Guide: Cross-validation - StratifiedKFold, cross_validate and cross_val_predict, consulted on 2026-11-12
- Saito and Rehmsmeier, The Precision-Recall Plot Is More Informative than the ROC Plot When Evaluating Binary Classifiers on Imbalanced Datasets, PLOS ONE (2015) - why the ROC can mislead with imbalanced classes, consulted on 2026-11-12
Commenti
Caricamento commenti...
Sign in to comment