Module 7 · Intermediate · Logistic regression

Confusion matrix, ROC curve and AUC explained

The confusion matrix, ROC curve and AUC explained with Python: read and plot a confusion matrix, draw ROC and precision-recall curves, and compare classifiers.

By theprogrammers team · · 7 min read

A single number like accuracy or F1 summarises a classifier, but it hides which mistakes the model makes and how its performance changes with the decision threshold. Two tools show the full picture:

  • The confusion matrix shows exactly how many examples of each class were predicted as each class.
  • The ROC curve and its AUC score show how well the model separates the classes across every possible threshold, which makes them ideal for comparing models.

This lesson explains both, plus the precision-recall curve, which is better for rare classes, with Python code and charts. It builds on accuracy, precision, recall and F1.

The setup

We'll use logistic regression as a spam filter on the Spambase data (4,601 emails described by 57 word and character frequencies), treating spam as the positive class:

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").

import numpy as np
import matplotlib.pyplot as plt
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

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.3, stratify=y, random_state=1)

clf = make_pipeline(StandardScaler(), LogisticRegression(max_iter=1000))
clf.fit(X_train, y_train)
y_pred = clf.predict(X_test)
y_score = clf.predict_proba(X_test)[:, 1]      # probability of spam

The labels are already 1 for spam and 0 for not spam, so spam is the positive class (1), as scikit-learn's metrics expect.

The confusion matrix

from sklearn.metrics import confusion_matrix

print(confusion_matrix(y_test, y_pred))
[[801  36]
 [ 56 488]]

Rows are the actual classes, columns are the predicted classes, both in order 0 then 1:

Predicted not spamPredicted spam
Actually not spam801 true negatives36 false positives
Actually spam56 false negatives488 true positives

The diagonal (top left to bottom right) holds the correct predictions. Everything off the diagonal is a mistake, and you can see which kind. Here the 36 false positives, real emails sent to the spam folder, are the costly mistake: someone could miss an important message. The 56 false negatives are spam emails that reached the inbox, which is annoying but less harmful.

From these four numbers:

  • Accuracy = (801 + 488) / 1,381 = 0.933
  • Precision = 488 / (488 + 36) = 0.931
  • Recall = 488 / (488 + 56) = 0.897

Plot it

from sklearn.metrics import ConfusionMatrixDisplay

ConfusionMatrixDisplay.from_predictions(
    y_test, y_pred, display_labels=["not spam", "spam"], cmap="Blues")
plt.title("Confusion matrix")
plt.show()
A 2 by 2 confusion matrix heatmap in blue: 801 emails that aren't spam predicted not spam and 488 spam emails predicted spam in dark squares on the diagonal, with 36 real emails predicted spam and 56 spam emails predicted not spam in pale squares.

For problems with many classes, the confusion matrix shows which classes get mixed up with each other: a digit classifier confusing 4s and 9s, say. Pass normalize="true" to show each row as proportions, which is easier to read when classes have different sizes.

The ROC curve

The confusion matrix is for one threshold, 0.5 by default. The ROC curve (receiver operating characteristic) shows what happens at every threshold. It plots:

  • True positive rate (recall): the share of positives caught, on the y-axis.
  • False positive rate: FP / (FP + TN), the share of negatives wrongly flagged, on the x-axis.
from sklearn.metrics import RocCurveDisplay

fig, ax = plt.subplots()
RocCurveDisplay.from_predictions(y_test, y_score, name="Logistic regression", ax=ax)
ax.plot([0, 1], [0, 1], ls="--", color="grey", label="Random guessing (AUC = 0.5)")
ax.legend()
ax.set_title("ROC curve")
plt.show()
A ROC curve that rises steeply from the bottom left to a true positive rate of about 0.9 at a false positive rate of under 0.05, then curves along the top, labelled with an AUC of 0.97, above a grey dashed diagonal line for random guessing.

How to read it:

  • Bottom left (0, 0): a very high threshold. Nothing is flagged, so no false alarms, but nothing is caught.
  • Top right (1, 1): a very low threshold. Everything is flagged, so everything is caught, with every negative a false alarm.
  • Top left corner (0, 1): perfect. Every positive caught with no false alarms.
  • The diagonal: random guessing.

The closer the curve hugs the top left corner, the better the model separates the classes.

AUC: one number for the whole curve

AUC (area under the ROC curve) summarises the curve as a single number from 0 to 1:

from sklearn.metrics import roc_auc_score

print(round(roc_auc_score(y_test, y_score), 3))
0.973
AUCMeaning
1.0Perfect separation
0.9 to 1.0Excellent
0.8 to 0.9Good
0.7 to 0.8Fair
0.5No better than random
Below 0.5Worse than random: the predictions are probably flipped

AUC has a neat meaning: it's the probability that the model gives a random positive example a higher score than a random negative one. An AUC of 0.973 means that if you pick one spam email and one real email at random, the model gives the spam one the higher spam probability 97.3% of the time.

Notice that roc_auc_score takes the probabilities (y_score), not the 0/1 predictions. AUC doesn't depend on any threshold, which makes it ideal for comparing models before you choose one.

Comparing models with ROC curves

from sklearn.tree import DecisionTreeClassifier
from sklearn.neighbors import KNeighborsClassifier

models = {
    "Logistic regression": clf,
    "Decision tree (depth 3)": DecisionTreeClassifier(max_depth=3, random_state=0),
    "KNN (k = 15)": make_pipeline(StandardScaler(), KNeighborsClassifier(15)),
}
fig, ax = plt.subplots()
for name, model in models.items():
    model.fit(X_train, y_train)
    RocCurveDisplay.from_estimator(model, X_test, y_test, name=name, ax=ax)
ax.plot([0, 1], [0, 1], ls="--", color="grey")
ax.set_title("Comparing classifiers")
plt.show()
Three ROC curves on one chart: logistic regression (AUC 0.97) and KNN (AUC 0.96) both rise steeply towards the top left corner, while the depth-3 decision tree's curve is lower and made of a few straight segments, with an AUC of 0.91.

The decision tree's curve is angular because a shallow tree outputs only a few distinct probabilities. KNN and decision trees have their own lessons in this module.

Precision-recall curves for rare classes

When the positive class is rare (fraud at 1%), ROC curves can look excellent even for a weak model, because there are so many negatives that the false positive rate stays tiny. The precision-recall curve focuses on the positive class and is more honest in that situation:

from sklearn.metrics import PrecisionRecallDisplay

fig, ax = plt.subplots()
PrecisionRecallDisplay.from_predictions(y_test, y_score, name="Logistic regression", ax=ax)
ax.set_title("Precision-recall curve")
plt.show()
A precision-recall curve that stays between about 0.95 and 1.0 precision as recall rises to about 0.8, then drops steeply to about 0.4 as recall reaches 1.0, labelled with an average precision of 0.96.

Its summary score is average precision (AP, roughly the area under this curve). A random model's AP equals the share of positives, so on a 1% fraud dataset, 0.01 is the baseline, not 0.5.

UseWhen
Confusion matrixTo see exactly which mistakes happen at your chosen threshold
ROC curve and AUCTo compare models when classes are reasonably balanced
Precision-recall curve and APWhen the positive class is rare

Practice

  1. A confusion matrix is [[50, 10], [5, 35]]. What are precision and recall for class 1?
Show the answer

TP = 35, FP = 10, FN = 5. Precision = 35 / 45 ≈ 0.78. Recall = 35 / 40 = 0.875.

  1. Why does roc_auc_score need probabilities rather than predicted labels?
Show the answer

The ROC curve is built by trying every threshold on the scores. With only 0/1 labels there's a single threshold, so you'd get one point instead of a curve, and a misleading AUC.

  1. A model has an AUC of 0.3. What might be wrong?
Show the answer

It ranks positives below negatives more often than not, so the labels or scores are probably flipped, for example using the probability of the wrong class. Flipping the scores would give an AUC of 0.7.

Interview questions

What is a confusion matrix?

A table comparing actual and predicted classes. For binary classification it holds true negatives, false positives, false negatives and true positives, from which accuracy, precision, recall and other metrics are calculated.

What does the ROC AUC represent?

The area under the curve of true positive rate against false positive rate across all thresholds. It equals the probability that a randomly chosen positive is scored higher than a randomly chosen negative. 0.5 is random and 1.0 is perfect.

When would you prefer a precision-recall curve over a ROC curve?

When the positive class is rare. ROC curves can look optimistic because the large number of negatives keeps the false positive rate low, while precision-recall curves show performance on the minority class directly.

What to learn next

  1. Learn a different kind of classifier in the k-nearest neighbours (KNN) algorithm.
  2. Revisit accuracy, precision, recall and F1.