← Learning guides

Worked tutorial · about 30 minutes

Work out precision and recall before choosing a threshold

Use ten fictional scores to build a confusion matrix, compare two review thresholds, and explain exactly which mistakes each choice makes.

Original editorial exercise · fictional practice data · checked 23 October 2026

Two classifiers can have the same accuracy while making different mistakes. Here you will compare two thresholds on one invented score table. The task is to flag cases for manual review: actual_positive=1 means a case needs review, and a score at or above the threshold means it gets flagged.

This exercise starts after scores exist. It does not train a model, prove that the scores are calibrated probabilities, or measure performance on real users. You can complete the calculations on paper; Python 3 is optional.

1. Download the scores and make a prediction column

case_id,actual_positive,score
R01,1,0.90
R02,0,0.80
R03,1,0.70
R04,0,0.60
R05,1,0.55
R06,0,0.45
R07,1,0.40
R08,0,0.30
R09,0,0.20
R10,0,0.10

At threshold 0.50, flag every row whose score is at least 0.50. Do not round scores before comparing. For each row, compare the prediction with its actual label, then assign exactly one outcome:

2. Check the denominators before the arithmetic

Precision asks what fraction of flagged cases truly needed review: TP / (TP + FP). Recall asks what fraction of all cases needing review were found: TP / (TP + FN). Accuracy is (TP + TN) / all cases. Write the fractions before converting them to percentages; changing a denominator changes the question.

The table contains four actual positives, regardless of your threshold. The number of flagged cases can change. If you get a different number of actual positives after changing the threshold, you have accidentally changed a label or counted predictions as labels.

3. Compare 0.50 with 0.85

Complete the blank worksheet first. Then open the worked answer and compare both the counts and the missed case IDs.

Show the worked comparison
Results on the ten invented cases
ThresholdTP / FP / FN / TNFlaggedPrecisionRecallAccuracy
0.503 / 2 / 1 / 453/5 = 60%3/4 = 75%7/10 = 70%
0.851 / 0 / 3 / 611/1 = 100%1/4 = 25%7/10 = 70%

At 0.50, R01–R05 are flagged. R02 and R04 are false alarms; R07 is missed. At 0.85, only R01 is flagged. There are no false alarms in this tiny table, but R03, R05 and R07 are missed.

Both choices get 70% accuracy. The higher threshold has cleaner flagged results here, while finding fewer of the cases that need review. A 100% precision result based on a single flagged case is weak evidence about future performance.

4. Reproduce the result in Python

python evaluate_threshold.py scores.csv 0.50
python evaluate_threshold.py scores.csv 0.85
python evaluate_threshold.py scores.csv 1.0

The checker only reads the CSV and prints JSON. At threshold 1.0, nothing is flagged: precision has a zero denominator and is reported as null, rather than inventing a perfect or zero precision score. Recall is zero because none of the four actual positives is found.

Show the complete checker
"""Evaluate invented classifier scores, without training or external requests.
Usage: python evaluate_threshold.py scores.csv 0.50
"""
import csv
import json
import math
import sys


def evaluate(filename, threshold):
    if not math.isfinite(threshold) or not 0 <= threshold <= 1:
        raise ValueError("Threshold must be between 0 and 1")
    counts = {"tp": 0, "fp": 0, "fn": 0, "tn": 0}
    seen = set()
    with open(filename, encoding="utf-8-sig", newline="") as stream:
        reader = csv.DictReader(stream)
        if reader.fieldnames != ["case_id", "actual_positive", "score"]:
            raise ValueError("Unexpected CSV header")
        for row in reader:
            case_id = row["case_id"]
            if not case_id or case_id in seen or row["actual_positive"] not in ("0", "1"):
                raise ValueError("Expected unique case IDs and binary labels")
            seen.add(case_id)
            actual, score = int(row["actual_positive"]), float(row["score"])
            if not math.isfinite(score) or not 0 <= score <= 1:
                raise ValueError("Scores must be finite numbers between 0 and 1")
            predicted = score >= threshold
            key = ("tp" if actual else "fp") if predicted else ("fn" if actual else "tn")
            counts[key] += 1
    tp, fp, fn, tn = (counts[key] for key in ("tp", "fp", "fn", "tn"))
    ratio = lambda numerator, denominator: numerator / denominator if denominator else None
    return {"threshold": threshold, **counts, "flagged": tp + fp,
            "precision": ratio(tp, tp + fp), "recall": ratio(tp, tp + fn),
            "accuracy": ratio(tp + tn, tp + fp + fn + tn)}


if __name__ == "__main__":
    if len(sys.argv) != 3:
        raise SystemExit("Usage: python evaluate_threshold.py scores.csv 0.50")
    print(json.dumps(evaluate(sys.argv[1], float(sys.argv[2])), indent=2))

5. Make a decision you can explain

If missed review cases are the main concern, 0.50 finds three rather than one in this example, with more false alarms. If you can inspect only one flagged case, 0.85 fits that capacity on this file, while missing three positives. Neither choice is universally better. State the cost of each error, review capacity, and what evidence you would need before using a threshold.

In a real project, choose a threshold using validation data and an agreed objective, then evaluate the frozen choice on a separate test set. Do not repeatedly tune to your final test results. These ten invented records demonstrate arithmetic only; a real evaluation needs representative labels, enough cases, and checks for the conditions in which the system will run.

Choose your next lesson

If the fractions were the obstacle, learn evaluation fundamentals before buying a model-building course. If counting was straightforward, practice a reproducible evaluation on a larger permitted dataset. For the separate problem of train/test leakage, use the existing customer-split exercise. For messy inputs, use the CSV audit tutorial. To compare learning routes, try the pre-course skills check.

Sources and scope

Definitions follow Google's Machine Learning Crash Course guide to classification metrics, checked 23 October 2026. Scores, counts, code and scenarios are our original practice material, not measured results from that course or a commercial model.