Module 6 · Intermediate · Logistic regression

Accuracy, precision, recall and F1

Classification metrics: accuracy, precision, recall and F1 score, the accuracy trap, the precision-recall trade-off, and when to use each.

By theprogrammers team · · 10 min read

A classifier that's "95% accurate" sounds great. But if 95% of emails are not spam, a model that never flags anything as spam is also 95% accurate, and completely useless. Accuracy alone can hide a broken model.

That's why classification uses several metrics: accuracy, precision, recall and the F1 score. Each answers a different question about the model's mistakes. Below: each one worked on a simple example, the same in scikit-learn, the trade-off between precision and recall, and a guide to choosing the right metric.

What you need first: logistic regression explained, which produces the probabilities and thresholds used here.

Key terms

  • Positive class: the class you care about finding, such as spam or fraud. The other is the negative class.
  • True positive (TP) / true negative (TN): a correct "yes" / a correct "no".
  • False positive (FP): a false alarm. False negative (FN): a miss.
  • Precision: of the items flagged, the share that were really positive.
  • Recall: of the real positives, the share that were flagged.
  • F1 score: one number combining precision and recall, low if either is low.
  • Imbalanced classes: one class is much rarer than the other.

Four kinds of prediction

For a yes/no problem, call the class you care about positive: spam, fraud, disease. Every prediction falls into one of four boxes:

Predicted positivePredicted negative
Actually positiveTrue positive (TP): caught itFalse negative (FN): missed it
Actually negativeFalse positive (FP): false alarmTrue negative (TN): correctly ignored

Every metric below is built from these four counts. Laid out as a grid, they form the confusion matrix, covered in detail in the next lesson.

Accuracy, precision, recall and F1 on a worked example

A spam filter checks 100 emails. 20 are really spam. The filter flags 18 emails as spam, of which 15 really are spam.

  • TP = 15 spam emails caught
  • FP = 3 good emails wrongly flagged (18 flagged − 15 correct)
  • FN = 5 spam emails missed (20 spam − 15 caught)
  • TN = 77 good emails correctly left alone (100 − 15 − 3 − 5)

Here are the same 100 emails as dots. Precision looks only inside the flagged box. Recall looks only at the orange dots.

One hundred emails as dots. The flagged box holds 18 dots: 15 orange spam and 3 grey good emails. Outside it are 5 orange spam emails that were missed and 77 grey good emails. Precision is 15 out of 18, 0.83, and recall is 15 out of 20, 0.75.

Accuracy

Accuracy = (TP + TN) / everything: the share of all predictions that were right.

(15 + 77) / 100 = 92%.

Simple and intuitive, but it treats every mistake the same, and it's misleading when classes are imbalanced.

Precision

Precision = TP / (TP + FP): of everything the model flagged, how much was right?

15 / 18 = 83%.

"When the filter says spam, it's right 83% of the time." High precision means few false alarms. It matters when false alarms are costly: a good email lost in the spam folder, an innocent customer's card blocked.

Recall

Recall = TP / (TP + FN): of all the real positives, how many did the model catch?

15 / 20 = 75%.

"The filter catches 75% of spam." Recall is also called sensitivity or the true positive rate. High recall means few misses. It matters when misses are costly: an undetected disease, a fraud that goes through.

F1 score

Precision and recall pull in opposite directions, so it helps to combine them. The F1 score is their harmonic mean:

F1 = 2 × precision × recall / (precision + recall)

2 × 0.833 × 0.75 / (0.833 + 0.75) = 0.79.

The harmonic mean is low if either number is low. A model with precision 1.0 and recall 0.01 gets an F1 of about 0.02, not the 0.5 an ordinary average would give. So F1 rewards models that do reasonably on both.

In scikit-learn

import numpy as np
from sklearn.metrics import (accuracy_score, precision_score,
                             recall_score, f1_score)

# 1 = spam, 0 = not spam: the 100 emails from the example
y_true = np.array([1] * 20 + [0] * 80)
y_pred = np.array([1] * 15 + [0] * 5 + [1] * 3 + [0] * 77)

print("Accuracy: ", accuracy_score(y_true, y_pred))
print("Precision:", round(precision_score(y_true, y_pred), 3))
print("Recall:   ", recall_score(y_true, y_pred))
print("F1:       ", round(f1_score(y_true, y_pred), 3))
Accuracy:  0.92
Precision: 0.833
Recall:    0.75
F1:        0.789

The arguments are always (true labels, predicted labels), and by default the positive class is 1.

The accuracy trap

Now a fraud dataset where only 1% of transactions are fraud. A "model" that always says "not fraud". Predict first: what will its accuracy be, and its recall?

y_true = np.array([1] * 10 + [0] * 990)       # 10 frauds in 1,000
lazy = np.zeros(1000, dtype=int)              # never predicts fraud

print("Accuracy:", accuracy_score(y_true, lazy))
print("Recall:  ", recall_score(y_true, lazy))
Accuracy: 0.99
Recall:   0.0

99% accurate, and it catches zero frauds. With imbalanced classes, always look at precision and recall (or F1) for the rare class. Handling imbalanced datasets covers how to fix models in this situation.

Experiment: the opposite lazy model flags every transaction as fraud. Recall is now perfect. Predict its precision and F1 before running:

paranoid = np.ones(1000, dtype=int)           # flags everything as fraud
print("Accuracy: ", accuracy_score(y_true, paranoid))
print("Recall:   ", recall_score(y_true, paranoid))
print("Precision:", precision_score(y_true, paranoid))
print("F1:       ", round(f1_score(y_true, paranoid), 3))
Accuracy:  0.01
Recall:    1.0
Precision: 0.01
F1:        0.02

Perfect recall, but precision is 0.01: 990 of the 1,000 alarms are false. F1 is 0.02, because the harmonic mean is dragged down by the tiny precision. Either metric on its own can be gamed by a lazy model; F1, or precision and recall read together, can't.

The classification report

classification_report prints all the metrics for every class at once. Here's a real model: logistic regression as a spam filter, on the Spambase data of 4,601 emails described by 57 word and character frequencies:

Download the data: spambase.csv (1.1 MB), or from the original source, the UCI Machine Learning Repository. The code below loads it for you, so you only need the file to open it in a spreadsheet or work offline: load it with pd.read_csv("spambase.csv").

from sklearn.datasets import fetch_openml
from sklearn.linear_model import LogisticRegression
from sklearn.model_selection import train_test_split
from sklearn.pipeline import make_pipeline
from sklearn.preprocessing import StandardScaler
from sklearn.metrics import classification_report

X, y = fetch_openml(data_id=44, as_frame=True, return_X_y=True)   # Spambase
y = y.astype(int)                                                  # 1 = spam, 0 = not spam
X_train, X_test, y_train, y_test = train_test_split(
    X, y, test_size=0.2, stratify=y, random_state=42)
clf = make_pipeline(StandardScaler(), LogisticRegression(max_iter=1000)).fit(X_train, y_train)

print(classification_report(y_test, clf.predict(X_test),
                            target_names=["not spam", "spam"]))
              precision    recall  f1-score   support

    not spam       0.93      0.95      0.94       558
        spam       0.92      0.90      0.91       363

    accuracy                           0.93       921
   macro avg       0.93      0.92      0.93       921
weighted avg       0.93      0.93      0.93       921
  • Each row treats that class as "positive".
  • support is how many test examples are in each class.
  • macro avg is the simple average across classes: every class counts equally, which is good for spotting a weak rare class.
  • weighted avg weights each class by its support.

The precision-recall trade-off

A classifier usually outputs a probability, and a threshold turns it into a yes or no. Lowering the threshold flags more items: recall goes up, precision goes down. Raising it does the opposite:

proba = clf.predict_proba(X_test)[:, 1]          # probability of spam

for threshold in [0.1, 0.3, 0.5, 0.7, 0.9]:
    pred = (proba >= threshold).astype(int)
    print(f"threshold {threshold}: precision {precision_score(y_test, pred):.2f}, "
          f"recall {recall_score(y_test, pred):.2f}")
threshold 0.1: precision 0.68, recall 0.98
threshold 0.3: precision 0.85, recall 0.93
threshold 0.5: precision 0.92, recall 0.90
threshold 0.7: precision 0.95, recall 0.81
threshold 0.9: precision 0.98, recall 0.61

You can't usually maximise both. At 0.1 the filter catches 98% of spam, but only 68% of the emails it moves are really spam: about a third of the spam folder would be real mail. At 0.9 it's almost never wrong (precision 0.98) but lets 39% of spam through.

Pick the threshold based on which mistake costs more. For a spam filter, a real email lost in the spam folder (a false positive) is worse than one spam in the inbox, so precision matters more and you'd choose 0.7 or even higher. For disease screening it's the other way round: missing a sick patient is the worse mistake, so you'd choose a low threshold for high recall.

Which metric should you use?

SituationFocus onWhy
Balanced classes, all mistakes cost about the sameAccuracySimple and fair here
False alarms are expensive (spam filter, blocking cards)PrecisionFew wrong flags
Misses are expensive (disease, fraud, safety)RecallFew missed cases
Imbalanced classes, both errors matterF1Balances precision and recall for the rare class
Comparing models before choosing a thresholdROC AUC or PR AUCThreshold-free; see ROC and AUC

If one type of error is costlier but the other still matters, the F-beta score (fbeta_score) weights recall beta times as much as precision: F2 favours recall, F0.5 favours precision.

Practice

  1. A model flags 50 transactions as fraud; 40 really are. There were 80 frauds in total. Calculate precision and recall.
Show the answer

Precision = 40 / 50 = 0.8. Recall = 40 / 80 = 0.5. The model is usually right when it flags fraud, but it misses half of it.

  1. What's the F1 score for precision 0.8 and recall 0.5?
Show the answer

2 × 0.8 × 0.5 / (0.8 + 0.5) = 0.8 / 1.3 ≈ 0.62.

  1. A hospital model screens for a rare disease. Which metric would you prioritise, and how would you adjust the threshold?
Show the answer

Recall: missing a sick patient is far worse than a false alarm, which a follow-up test can clear. Lower the threshold so more patients are flagged, while keeping precision acceptable.

  1. Using the spam model's threshold table, which threshold gives the highest F1? Compute it with f1_score for each threshold.
Show the answer
for threshold in [0.1, 0.3, 0.5, 0.7, 0.9]:
    pred = (proba >= threshold).astype(int)
    print(threshold, round(f1_score(y_test, pred), 3))
0.1 0.804
0.3 0.89
0.5 0.909
0.7 0.874
0.9 0.754

The default threshold, 0.5, gives the highest F1 here, 0.909. F1 weights precision and recall equally, so it peaks where they're roughly balanced (0.92 and 0.90). If false alarms matter more, as for a spam filter, the best threshold for your costs is higher than the best for F1.

  1. Two fraud models each have accuracy 0.99 on a dataset with 1% fraud. Model A has recall 0.0; model B has recall 0.6 and precision 0.5. Which would you deploy, and what does this say about accuracy?
Show the answer

Model B: it catches 60% of frauds, while A catches none. Their accuracies are equal because the rare class barely moves accuracy: missing all 10 frauds and making a handful of false alarms cost about the same number of rows. On imbalanced data, accuracy can't tell a useless model from a useful one.

Interview questions

What is the difference between precision and recall?

Precision is the share of predicted positives that are truly positive: TP / (TP + FP). Recall is the share of actual positives that were found: TP / (TP + FN). Precision measures false alarms; recall measures misses.

Why is accuracy misleading for imbalanced datasets?

A model can achieve high accuracy by always predicting the majority class while never detecting the minority class. Precision, recall, F1 or PR AUC for the minority class reveal this.

Why does F1 use the harmonic mean?

The harmonic mean is dominated by the smaller value, so F1 is only high when both precision and recall are high. An arithmetic mean would let one high value hide a very low one.

Key takeaways

  • Every classification metric comes from four counts: TP, FP, FN and TN.
  • Accuracy can look excellent on imbalanced data while the model catches nothing.
  • Precision counts false alarms; recall counts misses. Lowering the threshold raises recall and lowers precision.
  • F1 is the harmonic mean of the two, so it's only high when both are.
  • Choose the metric, and the threshold, from what each mistake costs.

Frequently asked questions

What is a good F1 score?

It depends on the problem and on how rare the positive class is. Compare against a baseline and other models on the same data; an F1 of 0.6 can be strong for rare fraud and weak for a clear-cut task.

Is recall the same as sensitivity?

Yes. Recall, sensitivity and true positive rate are three names for TP / (TP + FN). Medicine says sensitivity; machine learning usually says recall.

Which positive class does scikit-learn use?

By default, the label 1 (pos_label=1). If your labels are strings such as "spam", pass pos_label="spam", or the metric may describe the wrong class.

What to learn next

  1. See all four counts at once in the confusion matrix, ROC curve and AUC, the next lesson.
  2. Fix models for rare classes in handling imbalanced datasets.
  3. Revisit logistic regression.