Confusion matrix
Classification predicts a category instead of a continuous number. A package inspector may flag an item as damaged (1) or intact (0). A confusion matrix compares predicted labels with verified labels. It shows the kinds of errors that a single accuracy score hides. In this lesson, a positive prediction means a request for inspection, not proof of damage. All records are fictional.
Four possible outcomes
For each package, compare the verified label y with the predicted label p. A true positive (TP) is damage correctly flagged; a false positive (FP) is an intact package flagged; a false negative (FN) is damage missed; a true negative (TN) is an intact package correctly left unflagged. A matrix with actual labels as rows and predicted labels as columns, both ordered [0, 1], contains [[TN, FP], [FN, TP]]. Our teaching function returns a flat list [TP, FP, FN, TN] instead. Always label the axes and order: different presentations need not use the same layout.
Consider ten packages: five damaged and five intact. The inspector flags three damaged and one intact package. Two damaged packages are missed; four intact packages are not flagged. This gives TP=3, FP=1, FN=2, TN=4. All four counts sum to ten. Pair labels by package ID before producing the lists; equal list lengths alone do not prove correct alignment.
def confusion(actual, predicted): if len(actual) != len(predicted): raise ValueError("Lengths must match") if any(v not in (0, 1) for v in actual + predicted): raise ValueError("Binary labels required") tp = fp = fn = tn = 0 for y, p in zip(actual, predicted): if y == 1 and p == 1: tp += 1 elif p == 1: fp += 1 elif y == 1: fn += 1 else: tn += 1 return [tp, fp, fn, tn]
print(confusion([1,1,1,1,1,0,0,0,0,0], [1,1,1,0,0,1,0,0,0,0]))print(confusion([], []))The first line prints [3, 1, 2, 4]. Each loop iteration contributes to exactly one count. The second line shows that an empty paired list yields four zeros; this is a count, not evidence of perfect performance. The function accepts small lists of binary labels and rejects mismatched lengths or other label values. It does not validate record IDs.
Turn counts into metrics
Accuracy = (TP + TN) / N: the fraction of all decisions that are correct. Precision = TP / (TP + FP): among flagged packages, what fraction really have damage? Recall = TP / (TP + FN): among damaged packages, what fraction are flagged? F1 = 2TP / (2TP + FP + FN): the harmonic combination of precision and recall when defined, using the count formula. For the ten-package example these values are 7/10 = 0.70, 3/4 = 0.75, 3/5 = 0.60, and 6/9 ≈ 0.667. The denominators refer to different populations; do not interchange them.
def metrics(tp, fp, fn, tn): if any(type(n) is not int or n < 0 for n in (tp, fp, fn, tn)): raise ValueError("Nonnegative integer counts required") def ratio(a, b): return a / b if b else None return [ratio(tp + tn, tp + fp + fn + tn), ratio(tp, tp + fp), ratio(tp, tp + fn), ratio(2 * tp, 2 * tp + fp + fn)]
print([round(v, 3) for v in metrics(3,1,2,4)])print(metrics(0,0,5,95))The output first reports the four metrics rounded to three decimal places. Internally the calculations retain floating-point values. The second result represents 100 packages with five damaged: predicting intact for everyone yields 95% accuracy, no predicted positives (precision undefined), zero recall, and zero F1 under the count formula. Our explicit zero-denominator convention is None, meaning undefined, not zero. In particular if TP=FP=FN=0, F1 is undefined. Libraries may offer different policies; report the chosen policy and class support rather than silently replacing undefined values.
Beyond binary evaluation
A three-class sorter may label packages intact, dented or wet. Compute per-class metrics by treating the selected class as positive and all other classes as negative. Macro averaging gives each class equal weight; weighted averaging uses the actual class support as weights; micro averaging pools counts first. For single-label multiclass tasks with every class included, micro precision, recall and F1 equal accuracy. For example, 90 intact items all correctly labeled, nine dented items all missed, and one wet item correctly labeled yield per-class recalls 1, 0, 1, macro recall 2/3 and support-weighted recall 91/100. For undefined metrics, specify whether classes are excluded or assigned a value before averaging. These definitions do not extend unchanged to every multilabel setup.
Common mistakes and practice
Do not mistake recall for precision: increasing the number flagged can recover missed damage but also increase inspection workload. Do not compute metrics on training data and claim generalization. Report support and counts on held-out data. Practice: for TP=4, FP=2, FN=1, TN=13, calculate accuracy, precision, recall and F1. Check that the denominators are 20, 6, 5 and 11 respectively; results are 0.85, 2/3, 0.8 and 8/11. Next, learn how a threshold changes those counts.
Check Your Understanding
Solidify your learning with the interactive assessment directly below this lesson.
Concept Quiz & Questions
Confusion matrix quiz
Apply binary classification evaluation to new scenarios.
Actual label 1, predicted 0. Which outcome is this?
TP=3, FP=1, FN=2, TN=4. What is recall?
When there are no predicted positives, what does the lesson metrics helper return for precision?
For actual labels as rows and predicted labels as columns, order [0,1], what is the first row?
Which averaging method gives each class equal weight when all per-class metric values are defined?