Sub topic 1
Predictions versus true labels
Overview
Every classification metric in this tutorial is built from one thing: a pair of values for each example. One value is what actually happened, and the other is what the model said. Accuracy, precision, recall, and F1 are different ways of summarizing those pairs. If the pairs are wrong, every metric computed from them is wrong too.
This chapter covers the raw material. You will see what the true label and the prediction are, where each comes from, how they are lined up, and what can go wrong before you compute any metric. The next chapter turns the pairs into a confusion matrix.
Prerequisites
This chapter assumes you have:
- Basic Python, including lists,
zip, comprehensions, and functions. - The idea of supervised classification: a model learns from examples that already carry a correct answer.
- Some familiarity with train and test splits, meaning data held back from training so you can measure the model on examples it has not seen.
- Comfort with ratios and percentages.
The scikit-learn example later in the chapter needs scikit-learn installed. Everything else uses only the Python standard library.
The two sides of every example
A classifier assigns each example to one of a fixed set of classes. In a binary problem there are two classes, usually written as 1 (the positive class) and 0 (the negative class). Which class counts as "positive" is a choice you make. It is normally the class you are trying to find, such as a fraudulent transaction, a spam email, or a disease.
For each example you hold two values:
- The true label (also called the ground truth or the actual label) is the correct class, as recorded by a human, a lab test, or a later real-world outcome. By convention it is stored in
y_true. - The predicted label is the class the model chose. By convention it is stored in
y_pred.
Here is a small set of ten examples:
y_true = [1, 0, 1, 1, 0, 0, 0, 0, 0, 1]
y_pred = [1, 0, 0, 1, 0, 1, 0, 0, 0, 1]
for i, (t, p) in enumerate(zip(y_true, y_pred)):
status = "match" if t == p else "MISMATCH"
print(i, t, p, status)Running it prints one line per example. Examples 2 and 5 are marked MISMATCH, and the other eight match. In example 2 the true label is 1 and the model said 0, so the model missed a positive. In example 5 the true label is 0 and the model said 1, so the model raised a false alarm. These two kinds of mismatch are different mistakes. Most of this tutorial is about telling them apart.
A single number such as "8 of 10 match" hides that difference. That is why the chapters that follow split the pairs into four groups instead of two.
Where the true labels come from
True labels are not magic. They come from somewhere, and their quality limits what any metric can tell you.
- Human annotation. People label images, texts, or records. Annotators can disagree or make mistakes, so some labels are wrong.
- Delayed outcomes. A loan is labeled "defaulted" only months after approval. The label exists, but it arrives late.
- Measurements. A lab test or a sensor reading acts as the ground truth for a model that predicts from cheaper inputs.
- Proxies. Sometimes the recorded label is only a stand-in for what you care about. For example, "was investigated" stands in for "was fraudulent". Fraud that nobody investigated is recorded as not fraud.
A metric measures agreement with the recorded labels, not agreement with reality. When labels are noisy or biased, a model can score well by copying the bias, or score poorly because the label was wrong and the model was right.
Where the predictions come from
Most models do not output a class directly. They output a score, a number that grows with the model's confidence in the positive class. Logistic regression, gradient boosting, and neural networks typically produce a probability-like value between 0 and 1. A rule then converts the score into a class:
- Pick a decision threshold, a cutoff value. The common default is 0.5.
- Predict 1 if the score is at least the threshold, otherwise predict 0.
y_true = [1, 0, 1, 1, 0, 0, 0, 0, 0, 1]
scores = [0.92, 0.15, 0.40, 0.81, 0.05, 0.55, 0.20, 0.10, 0.30, 0.67]
threshold = 0.5
y_pred = [int(s >= threshold) for s in scores]
print(y_pred) # [1, 0, 0, 1, 0, 1, 0, 0, 0, 1]The result is the same y_pred used earlier. Example 2 has a score of 0.40, below the cutoff, so it becomes a 0. Example 5 has a score of 0.55, above the cutoff, so it becomes a 1.
The threshold is a separate choice from the model. The same model, with the same scores, produces different predictions at a different threshold, and so different metric values. A later chapter explores that effect. For now, remember that a "prediction" is the combination of a model and a threshold.
Alignment: the pairing must be exact
The metrics assume that position i in y_true and position i in y_pred describe the same example. Nothing in the numbers enforces this. If you shuffle one list and not the other, or you drop rows from one, the pairs are wrong and the code still runs. The metrics will be meaningless but will look plausible.
Common ways to break alignment:
- Shuffling features and labels separately.
- Filtering rows (for example, dropping missing values) from the features but not from the labels.
- Predicting on a dataframe whose index has been reordered, then comparing with labels in the original order.
- Mixing predictions from one split with labels from another.
A defensive habit is to keep the example identifier next to both values and check it, or to build the pairs from a single source in one place. At minimum, validate the inputs before you compute anything:
def check_inputs(y_true, y_pred):
if len(y_true) != len(y_pred):
raise ValueError(
f"length mismatch: {len(y_true)} true labels, {len(y_pred)} predictions"
)
if len(y_true) == 0:
raise ValueError("no examples to evaluate")
unexpected = (set(y_true) | set(y_pred)) - {0, 1}
if unexpected:
raise ValueError(f"unexpected labels: {sorted(unexpected, key=str)}")
check_inputs([1, 0, 1], [1, 0, 0]) # passes silently
try:
check_inputs([1, 0, 1], [1, 0])
except ValueError as e:
print(e) # length mismatch: 3 true labels, 2 predictionsNote that zip stops at the shorter list without raising an error. A length mismatch therefore silently drops examples if you rely on zip alone, which is why the explicit length check matters.
Encoding the labels consistently
Labels may be integers (0, 1), booleans (False, True), or strings ("spam", "ham"). Three rules keep comparisons sane:
- Use the same encoding on both sides. The string
"1"is not equal to the integer1, so a comparison between them reports a mismatch even when the model is right. - Decide which class is positive and keep it fixed. Precision and recall are defined relative to the positive class. Swap the roles and they change.
- Be careful with the order of classes. Libraries sort class labels, so
0comes before1and"ham"comes before"spam". Output arranged by class order can then put the negative class first.
The mismatch of types is a classic silent bug:
y_true = [1, 0, 1]
y_pred = ["1", "0", "0"]
print([t == p for t, p in zip(y_true, y_pred)]) # [False, False, False]Every comparison fails, including the two examples where the model was right, because an integer never equals a string. The data looks fine when you print it, which makes the error easy to miss.
Predictions on which data?
The pairs are only informative if the model has not seen those examples during training. A model can memorize its training data. Predictions on the training set mostly show how well the model remembers, not how well it will do on new inputs.
This is why the standard workflow splits the data first, trains on one part, and builds y_true and y_pred from the held-out part:
from sklearn.datasets import make_classification
from sklearn.linear_model import LogisticRegression
from sklearn.model_selection import train_test_split
X, y = make_classification(n_samples=200, n_features=5, random_state=0)
X_train, X_test, y_train, y_test = train_test_split(
X, y, test_size=0.25, stratify=y, random_state=0
)
model = LogisticRegression()
model.fit(X_train, y_train)
y_true = y_test # true labels for unseen examples
y_pred = model.predict(X_test) # hard class predictions
scores = model.predict_proba(X_test)[:, 1] # score for the positive class
print(len(y_true), len(y_pred), len(scores)) # 50 50 50A few details are worth noting:
stratify=ykeeps the share of each class about the same in the train and test parts. This matters a lot when one class is rare.predictreturns hard labels, which are the 0 or 1 decisions.predict_probareturns one column per class, ordered likemodel.classes_. Column 1 is the score for class 1 here because the classes are[0, 1].- For this model,
predictuses a 0.5 cutoff on the probability, so thresholdingscoresat 0.5 gives the same labels aspredict.
If you are tuning settings such as the threshold, you also need a separate validation set. Otherwise the test set stops being a fair check. The last chapter returns to this pitfall.
Hard labels versus scores
You now have two kinds of model output, and they support different metrics.
| Output | What it is | Metrics it supports |
|---|---|---|
| Hard label (`y_pred`) | A class decision, 0 or 1 | Accuracy, precision, recall, F1 |
| Score (`scores`) | A number, higher means more likely positive | Everything above at any threshold, plus ranking metrics |
The metrics in this tutorial work on hard labels. Because a hard label depends on a threshold, one set of scores can yield many different sets of metrics. Always report which threshold you used, even if it is the default.
Edge cases to check early
Before computing any metric, look at your pairs for these situations:
- Empty input. With no examples there is nothing to measure, and a ratio would divide by zero.
- A class that never appears in
y_true. If the test set contains no positives, recall has no meaning, because there is nothing to find. - A class that never appears in
y_pred. If the model never predicts the positive class, precision has no meaning, because it made no positive claims to judge. - Very small test sets. With ten examples, one flipped prediction moves a percentage metric by ten points. Treat the numbers as rough.
- Duplicated or leaked examples. If the same record appears in both train and test, the test is not independent and the pairs look better than they should.
A quick count of each class on both sides catches most of these:
from collections import Counter
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(Counter(y_true)) # Counter({0: 6, 1: 4})
print(Counter(y_pred)) # Counter({0: 5, 1: 5})The true labels hold 4 positives and 6 negatives. The model predicted 5 positives and 5 negatives. The counts differ, which already tells you the model over-predicts the positive class on this sample. A matching count does not mean the model is correct, though, because the right number of positives could still be assigned to the wrong examples.
Summary of the working model
- Each evaluated example contributes one pair: a true label and a predicted label.
- True labels come from annotation, outcomes, or measurement, and their quality caps the value of every metric.
- Predictions usually come from a score plus a threshold, so a prediction depends on both the model and the cutoff.
- The two lists must line up position by position, use the same encoding, and cover held-out data.
- Mismatches come in two kinds, missed positives and false alarms, and the next chapter gives them names and counts.
Exercise
A model gives these scores for six examples whose true labels are ytrue = [1, 1, 0, 0, 1, 0]: scores = [0.80, 0.45, 0.60, 0.10, 0.55, 0.30]. Using a threshold of 0.5, write the list ypred and say which examples are mismatches and what kind of mistake each one is.
Show answer
At a threshold of 0.5, y_pred = [1, 0, 1, 0, 1, 0]. Example 1 (index 1) is a mismatch: the true label is 1 and the prediction is 0, so the model missed a positive. Example 2 (index 2) is a mismatch: the true label is 0 and the prediction is 1, so the model raised a false alarm. The other four examples match.
Exercise
A colleague computes metrics with ytrue = [1, 0, 1, 0] and ypred = ["1", "0", "1", "0"], where the predictions are strings. A hand-written comparison reports 0 matches. Explain why, and name two other checks, besides encoding, that you would run on the pairs before computing any metric.
Show answer
In Python the integer 1 does not equal the string "1", so every comparison is False even though the model is right on all four examples. Fix this by using the same type on both sides, for example by converting the predictions with int. Two other checks are comparing the lengths of the two lists (since zip silently truncates to the shorter one) and counting the classes in ytrue and ypred to confirm that each class appears and that nothing outside {0, 1} is present.