Sub topic 4
Accuracy: the share of correct predictions
Accuracy is the first number most people compute from a confusion matrix. It is simple and often useful, but it hides a lot. This chapter shows exactly how it is built from the cells, what it tells you, and where it stops telling you anything.
This chapter assumes you know what supervised classification is. It also assumes you are comfortable with fractions and ratios and can read short Python snippets. You should already know the four outcomes (TP, FP, FN, TN) and how the matrix is laid out.
Definition
Accuracy is the number of correct predictions divided by the total number of predictions. In a binary matrix, the correct predictions are the true positives and the true negatives:
accuracy = (TP + TN) / (TP + TN + FP + FN)
The complement is the error rate: (FP + FN) / total, which equals 1 minus accuracy. Both numbers describe the same split of the data, so reporting one gives you the other.
On the matrix, the correct predictions sit on the main diagonal, running from top left to bottom right. The wrong predictions sit off the diagonal. That is why accuracy is the sum of the diagonal divided by the sum of all cells.
A worked example
We use the same ten examples as earlier in this tutorial. Rows are actual labels and columns are predicted labels, which is the scikit-learn layout.
from sklearn.metrics import confusion_matrix, accuracy_score
y_true = [1, 0, 1, 1, 0, 0, 1, 0, 0, 0]
y_pred = [1, 0, 0, 1, 0, 1, 1, 1, 0, 0]
cm = confusion_matrix(y_true, y_pred, labels=[0, 1])
print(cm)
# [[4 2]
# [1 3]]
tn, fp, fn, tp = cm.ravel()
by_formula = (tp + tn) / (tp + tn + fp + fn)
by_diagonal = cm.trace() / cm.sum()
by_library = accuracy_score(y_true, y_pred)
print(by_formula, by_diagonal, by_library) # 0.7 0.7 0.7Seven of the ten predictions are correct: four true negatives and three true positives. The three errors are two false positives and one false negative. All three routes give 0.7, so you can pick whichever is convenient. The diagonal form, cm.trace() / cm.sum(), is the one that generalizes to more than two classes.
Accuracy does not depend on matrix orientation
Precision and recall change if you read the matrix the wrong way round. Swapping the axes turns false positives into false negatives, so the two metrics swap values. Accuracy does not change. Transposing a matrix leaves its diagonal in place, and the total is the same.
This has a practical consequence. If your accuracy looks right but your recall looks like what you expected for precision, suspect a transposed matrix. Accuracy cannot reveal an axis mix-up, so do not use it to confirm that you have read the matrix correctly.
Accuracy in a multiclass matrix
The definition does not change with more classes: correct predictions over all predictions. The correct predictions are still the diagonal. Here is the three-class example.
from sklearn.metrics import confusion_matrix, accuracy_score
labels = ["bird", "cat", "dog"]
y_true = ["cat", "cat", "cat", "dog", "dog", "dog", "bird", "bird", "bird", "bird"]
y_pred = ["cat", "cat", "dog", "dog", "dog", "dog", "bird", "cat", "bird", "bird"]
cm = confusion_matrix(y_true, y_pred, labels=labels)
print(cm)
# [[3 1 0]
# [0 2 1]
# [0 0 3]]
print(cm.trace(), cm.sum()) # 8 10
print(cm.trace() / cm.sum()) # 0.8
print(accuracy_score(y_true, y_pred)) # 0.8The diagonal holds 3 + 2 + 3 = 8 correct predictions out of 10. In multiclass work there are no single "TP" and "TN" cells for the whole model, so the formula using those names applies only to a binary matrix. The diagonal form works for both.
Accuracy is one number for the whole model. It will not tell you that the 0.8 hides one bird mistaken for a cat and one cat mistaken for a dog. For that you read the off-diagonal cells, which a later chapter covers.
What accuracy is made of
Accuracy mixes two kinds of success: finding positives and rejecting negatives. It weights them by how common each class is. Let prevalence be the fraction of examples that are actually positive. Then:
accuracy = prevalence × recall + (1 − prevalence) × specificity
You can check this on the worked example.
from sklearn.metrics import confusion_matrix
y_true = [1, 0, 1, 1, 0, 0, 1, 0, 0, 0]
y_pred = [1, 0, 0, 1, 0, 1, 1, 1, 0, 0]
tn, fp, fn, tp = confusion_matrix(y_true, y_pred, labels=[0, 1]).ravel()
n = tn + fp + fn + tp
prevalence = (tp + fn) / n # 4 / 10 = 0.4
recall = tp / (tp + fn) # 0.75
specificity = tn / (tn + fp) # 4 / 6
mixed = prevalence * recall + (1 - prevalence) * specificity
print(round(mixed, 3)) # 0.7The result matches 0.7. The identity explains why accuracy moves when the class mix moves, even if the model is unchanged. A model with fixed recall and specificity will score a different accuracy on a test set with a different share of positives. When you compare accuracy numbers from two datasets, first check that their class proportions are similar.
Reading an accuracy number
A bare accuracy value, such as 0.7, has no meaning without a reference point. Ask what a trivial model would score. The simplest baseline always predicts the most common class. Its accuracy equals the share of that class.
from collections import Counter
y_true = [1, 0, 1, 1, 0, 0, 1, 0, 0, 0]
model_accuracy = 0.7
counts = Counter(y_true)
baseline = max(counts.values()) / len(y_true)
print(counts) # Counter({0: 6, 1: 4})
print(baseline) # 0.6
print(model_accuracy - baseline) # about 0.1The model gains about ten points over always guessing "0". That is a modest improvement, and it is the fair way to describe the 0.7. If the baseline were 0.95, a model scoring 0.95 would add nothing at all. The next chapter works through exactly that case.
Common errors
- Reading accuracy as quality on the class you care about. Accuracy counts all classes equally. A model can score well while handling the rare, important class badly.
- Ignoring the cost of each error type. Accuracy treats a false positive and a false negative as the same size of mistake. In many tasks they are not. A missed disease and a false alarm have different consequences.
- Skipping the baseline. Always compare to the majority-class rate before calling a number good or bad.
- Comparing across different test sets. The prevalence term in the identity above means accuracy shifts with the class mix.
- Using the binary formula on a multiclass matrix. Use the trace divided by the sum.
- Computing accuracy on the training data. A model can memorize its training set. Report accuracy on held-out data.
- Rounding too early. With small test sets, one example changes accuracy by a visible amount. On 10 examples, one flipped prediction moves accuracy by 0.1. Report the test set size next to the number.
When accuracy is the right choice
Accuracy is a reasonable headline metric when three conditions hold:
- The classes are roughly balanced.
- The two kinds of error cost about the same.
- You want a single easy-to-explain number for the whole model.
When any of these fails, use accuracy together with precision, recall, or specificity, which the following chapters introduce. The matrix itself is always the better record. Accuracy is a summary of it, and you can always recompute the summary from the matrix, but you cannot rebuild the matrix from the summary.
Exercises
Exercise
A binary classifier produces this matrix in scikit-learn layout (rows are actual, columns are predicted, classes ordered 0 then 1): [[50, 10], [5, 35]]. Compute its accuracy and its error rate.
Show answer
The diagonal is 50 + 35 = 85. The total is 50 + 10 + 5 + 35 = 100. Accuracy is 85 / 100 = 0.85, and the error rate is 15 / 100 = 0.15.
Exercise
You transpose the matrix from the previous exercise by mistake, giving [[50, 5], [10, 35]]. Does accuracy change? Does recall for class 1 change?
Show answer
Accuracy does not change. The diagonal is still 85 and the total is still 100, so it stays 0.85. Recall for class 1 does change. Correctly oriented, it is 35 / (5 + 35) = 0.875. In the transposed matrix, the same formula gives 35 / (10 + 35), about 0.778, which is really the original precision.
Exercise
A test set has 90% negatives. A model has recall 0.50 and specificity 0.95. Use the identity accuracy = prevalence × recall + (1 − prevalence) × specificity to find its accuracy, then say whether it beats the majority-class baseline.
Show answer
Prevalence is 0.10. Accuracy = 0.10 × 0.50 + 0.90 × 0.95 = 0.05 + 0.855 = 0.905. The majority-class baseline is 0.90, so the model beats it by only half a point, even though it looks strong at 0.905.