Sub topic 3
Accuracy: the share of correct predictions
This chapter assumes you can write basic Python, know what supervised classification with labeled data is, and know why a model is scored on a held-out test set. It also assumes you have read the previous chapter on the confusion matrix. Accuracy is the simplest metric built from those four counts. It is also the one most often misused, so it helps to know exactly what it measures.
What accuracy measures
Accuracy is the fraction of predictions that match the true label:
accuracy = correct predictions / total predictionsTake 10 test examples. If the model gets 8 right, accuracy is 8 / 10 = 0.8, or 80%. The metric ignores which kind of mistake the model made, which class the example belonged to, and how confident the model was. It only asks whether the prediction equals the label.
The complement of accuracy is the error rate:
error rate = 1 - accuracy = incorrect predictions / total predictionsSome teams report error rate instead because it moves in the direction of "lower is better". The two carry the same information.
Accuracy from the confusion matrix
The confusion matrix splits the predictions into four groups. A prediction is correct in exactly two of them, true positives (TP) and true negatives (TN). It is wrong in the other two, false positives (FP) and false negatives (FN). So:
accuracy = (TP + TN) / (TP + FP + TN + FN)The denominator is the sum of all four cells, which is the number of test examples. The numerator is the diagonal of the matrix, where the predicted class equals the true class.
| Cell | Counts as | Part of accuracy |
|---|---|---|
| TP | Positive predicted, positive true | Numerator |
| TN | Negative predicted, negative true | Numerator |
| FP | Positive predicted, negative true | Denominator only |
| FN | Negative predicted, positive true | Denominator only |
Here is the flow from raw labels to a single number.
A worked example
This is the same 10-example data set used in the previous chapter. The label 1 is the positive class.
y_true = [1, 0, 1, 1, 0, 0, 0, 0, 0, 1]
y_pred = [1, 0, 0, 1, 0, 1, 0, 0, 0, 1]
tp = sum(t == 1 and p == 1 for t, p in zip(y_true, y_pred))
fp = sum(t == 0 and p == 1 for t, p in zip(y_true, y_pred))
tn = sum(t == 0 and p == 0 for t, p in zip(y_true, y_pred))
fn = sum(t == 1 and p == 0 for t, p in zip(y_true, y_pred))
from_cells = (tp + tn) / (tp + fp + tn + fn)
direct = sum(t == p for t, p in zip(y_true, y_pred)) / len(y_true)
print(tp, fp, tn, fn) # 3 1 5 1
print(from_cells, direct) # 0.8 0.8The cells are TP=3, FP=1, TN=5, FN=1. The model is correct on 3 + 5 = 8 of 10 examples, so accuracy is 0.8. The direct comparison t == p gives the same answer without building the matrix. That shortcut works because "correct" means exactly "the prediction equals the label". Use whichever is clearer in your code. The shortcut also works unchanged when there are more than two classes.
A habit worth building is to compute accuracy both ways at least once on a new pipeline. If the two numbers disagree, the labels are probably in a different order or type than you assumed, for example strings in one list and integers in the other.
Computing accuracy with scikit-learn
accuracy_score in scikit-learn takes the true labels first and the predictions second.
from sklearn.metrics import accuracy_score
y_true = [1, 0, 1, 1, 0, 0, 0, 0, 0, 1]
y_pred = [1, 0, 0, 1, 0, 1, 0, 0, 0, 1]
print(accuracy_score(y_true, y_pred)) # 0.8
print(accuracy_score(y_true, y_pred, normalize=False)) # 8With normalize=False, the function returns the number of correct predictions instead of the fraction. This is useful when you want to report "8 of 10" or compare raw counts across runs.
The function also accepts sample_weight. Each example then contributes its weight to the numerator if it was correct, and to the denominator always. This is how you make some examples count more, for instance recent data or high-value customers.
from sklearn.metrics import accuracy_score
y_true = [1, 0, 1, 1, 0, 0, 0, 0, 0, 1]
y_pred = [1, 0, 0, 1, 0, 1, 0, 0, 0, 1]
weights = [1, 1, 3, 1, 1, 1, 1, 1, 1, 1] # the third example counts three times
print(round(accuracy_score(y_true, y_pred, sample_weight=weights), 3)) # 0.667The third example is one of the two misclassified ones. With its weight raised to 3, the wrong weight is 3 + 1 = 4 out of a total of 12, so weighted accuracy falls from 0.8 to 8 / 12, which is about 0.667. Be aware that sample_weight is a modeling decision, not a detail. Report it whenever you use it.
Accuracy with more than two classes
Accuracy needs no special handling for multiclass problems. A prediction is correct if it equals the true class, whatever the number of classes.
from collections import Counter
from sklearn.metrics import accuracy_score
y_true = [0, 1, 2, 2, 1, 0]
y_pred = [0, 2, 2, 2, 1, 1]
print(round(accuracy_score(y_true, y_pred), 3)) # 0.667
majority_share = max(Counter(y_true).values()) / len(y_true)
print(round(majority_share, 3)) # 0.333Four of six predictions match, so accuracy is 0.667. The second printed value is the accuracy of a model that always predicts the most common class. That brings us to the idea of a baseline.
Accuracy needs a baseline
A bare accuracy number has no meaning until you know what a trivial model would score. The usual trivial model always predicts the most frequent class in the training data. Its accuracy equals the share of that class.
- On a 50/50 data set, the baseline is 0.5. An accuracy of 0.8 is a real improvement.
- On a data set where 95% of examples are negative, the baseline is 0.95. An accuracy of 0.8 is then worse than doing nothing.
- On a three-class data set with equal classes, the baseline is about 0.33.
In practice, report accuracy next to the majority-class baseline, so a reader can judge the gain. The next chapter shows how this goes wrong on imbalanced data. For now, remember that accuracy is only interpretable relative to the class distribution.
What accuracy treats as equal
Accuracy gives every example the same weight, and it gives FP and FN the same cost. Both are simply "wrong". This is fine when the following are true:
- The classes are roughly balanced.
- A false alarm and a missed case do about the same harm.
- You want one overall number for a quick comparison between models.
It is a poor choice when the two errors have different costs. Think of a spam filter that hides a real message, compared with one that lets a spam message through. The same accuracy can hide very different error patterns. Two models with 0.8 accuracy might have (FP=1, FN=1) and (FP=2, FN=0). The score cannot tell them apart. The chapters on precision, recall, and error costs address this.
Accuracy depends on the decision threshold
Many classifiers output a score or probability, not a label. A label is produced by comparing that score with a threshold, often 0.5. Accuracy is computed on the labels, so it changes when you move the threshold. Changing the threshold turns some TP into FN and some FP into TN, and the reverse. A model's accuracy is therefore a property of the model together with its threshold, not of the model alone. A later chapter covers the threshold in detail. For now, state the threshold whenever you report accuracy from a probabilistic model.
How much to trust a single accuracy number
Accuracy measured on a test set is an estimate of the model's accuracy on future data. With few test examples, the estimate is noisy. A rough guide is the standard error of a proportion:
standard error = sqrt(p * (1 - p) / n)where p is the measured accuracy and n is the number of test examples.
from math import sqrt
p = 0.8
for n in (10, 1000):
se = sqrt(p * (1 - p) / n)
print(n, round(se, 3))
# 10 0.126
# 1000 0.013With 10 examples, an accuracy of 0.8 is uncertain by roughly ±0.13 (one standard error). With 1000 examples, it is about ±0.013. So a model that scores 0.80 on 10 examples and another that scores 0.85 on the same 10 are not clearly different. This normal approximation is rough for very small n or for accuracies near 0 or 1, but it shows why you should not read much into small differences on small test sets.
Common mistakes
- Swapping the argument order.
accuracy_score(y_pred, y_true)returns the same number, because accuracy is symmetric. This habit breaks silently for precision and recall, where the order matters. Always write true labels first. - Mismatched label types. Comparing
"1"(a string) with1(an integer) counts every example as wrong, giving an accuracy of 0. Check the types if you see a surprisingly low value. Scikit-learn raises an error when it detects mixed types in some cases, but plain Python comparisons do not. - Comparing models on different test sets. Accuracy values are only comparable when they come from the same examples.
- Reporting accuracy without class counts. Always show how many examples fall in each class.
- Treating a small gain as real. A difference of one or two examples on a small test set is within noise.
Summary
- Accuracy is correct predictions divided by all predictions, which is (TP + TN) / (TP + FP + TN + FN).
- The error rate is 1 minus accuracy.
accuracy_score(y_true, y_pred)computes it, andnormalize=Falsereturns the count instead.- Accuracy works the same way for any number of classes.
- It is only meaningful next to a majority-class baseline.
- It treats FP and FN as equally costly and depends on the decision threshold.
- A small test set makes the number noisy.
Exercise
A test set has 200 examples. The model's confusion matrix has TP=30, FP=10, TN=150, FN=10. (a) What is the accuracy? (b) A model that always predicts the negative class has what accuracy on this test set? (c) Is the first model's improvement over that baseline large or small?
Show answer
(a) Accuracy = (30 + 150) / 200 = 180 / 200 = 0.9. (b) There are 150 + 10 = 160 negatives out of 200, so always predicting negative gives 160 / 200 = 0.8. (c) The model gains 0.1 over the baseline. It looks modest, so accuracy alone understates how much work the model does on the 40 positive examples, which later chapters measure with precision and recall.
Exercise
Two models are evaluated on the same 10 examples. Model A has FP=1 and FN=1 and gets 8 correct. Model B has FP=2 and FN=0. Do they have the same accuracy? What does accuracy fail to show?
Show answer
Model B has 10 - 2 = 8 correct, so both models have accuracy 0.8. Accuracy cannot show that Model A misses one real positive while Model B misses none but raises two false alarms. Which model is better depends on the cost of each error type.