Chapter DPrediction: your first ML ideaPage 1 of 8

Prediction: your first ML idea

Define the lab goal and success criteria

Binary prediction turns scores into labels with a threshold, then compares those labels with known truth using explicit metrics.

~13 minLab goal

1Try it yourself

Playground

Prediction: your first ML idea

Tune a tiny rule-based “model.” Watch accuracy change.

75% accuracy
  • Mom: dinner at 7

    Pred: not spam · Truth: not spam ·

  • URGENT!!! click now to WIN money

    Pred: spam · Truth: spam ·

  • School homework reminder

    Pred: spam · Truth: not spam ·

  • FREE FREE FREE act immediately!!!

    Pred: spam · Truth: spam ·

Before you start

Why this matters

Before running anything, predict one observable result from the case: five examples have truth labels and confidence scores; the threshold must be tuned without pretending the tiny set proves generalization. Write the prediction beside the command or code line that should cause it. This makes the session an experiment rather than a transcription exercise.

2Learn the idea

Read

Explain the chapter step

Begin by writing the success condition in observable terms. For this case, success is not familiarity with the vocabulary; it is producing a threshold evaluator that reports predictions, accuracy, and the confusion counts behind that accuracy. Record the starting state so you can distinguish an improvement from a result that was already present.

On this page, the practical job is to state a measurable outcome before changing anything. The running case is five examples have truth labels and confidence scores; the threshold must be tuned without pretending the tiny set proves generalization.

Read

Run the working example

truth = [1, 0, 1, 1, 0]
scores = [0.8, 0.3, 0.6, 0.9, 0.2]
threshold = 0.5
preds = [int(score >= threshold) for score in scores]

pairs = list(zip(truth, preds))
tp = pairs.count((1, 1)); fp = pairs.count((0, 1))
tn = pairs.count((0, 0)); fn = pairs.count((1, 0))
accuracy = (tp + tn) / len(pairs)
print(preds, f"accuracy={accuracy:.2f}", tp, fp, tn, fn)

Expected evidence:

[1, 0, 1, 1, 0] accuracy=1.00 3 0 2 0

The output may include version-specific details such as hashes, paths, fitted thresholds, or final decimal places. Compare the structural facts described here rather than copying placeholders. If the structure differs, stop and inspect the earliest unexpected line.

Read

Read it line by line

  1. the comparison returns Boolean values and int converts them to zero or one.
  2. zip aligns each known label with exactly one prediction.
  3. the four tuple counts partition every example into confusion-matrix cells.
  4. accuracy divides correct cells by all evaluated pairs; formatting shows two decimal places.

These lines form one chain: binary truth labels, scores between zero and one, and a chosen threshold becomes binary predictions plus accuracy, true positives, false positives, true negatives, and false negatives. Change only one input first. When several values change together, you cannot tell which change caused the new behavior.

Read

Common errors and fixes

  • First failure: zip silently stops at the shorter list, so assert equal lengths before scoring. Re-run the smallest command that proves the repair.
  • Second failure: an empty list causes division by zero and is not a meaningful evaluation. Preserve the failing input as a test when it represents a realistic mistake.
  • Misleading success: choosing a threshold after repeatedly inspecting the same labels overfits the evaluation set even though no model weights changed. A clean-looking final line cannot cancel contradictory intermediate evidence.

When debugging, copy the exact error text and inspect names, paths, shapes, types, and versions. Explain the cause in one sentence before changing code. That discipline prevents a guessed repair from creating a second defect.

Read

Evidence for this stage

Sweep thresholds such as 0.3, 0.5, and 0.7, but report all confusion counts. Then freeze the threshold and score a separate set. When false positives and false negatives have different costs, accuracy alone is insufficient.

For the current explain step, save the smallest useful evidence: the relevant command, its output, and the input that produced it. Do not use a screenshot as the only record when text can be copied and searched. Keep generated artifacts separate from source inputs so rerunning the example does not destroy the evidence it is meant to evaluate.

Package the evaluator with boundary tests and a short metric note. Downstream users need the threshold, score range, positive-class meaning, and date of the evaluation data.

Read

Reflect on the result

Return to your opening prediction. Mark it correct or rewrite it with the condition you missed. Then explain the difference between a successful execution and a trustworthy result for this specific example.

Checking tutor…

Continue learning · glossary & guides
  1. Which line or command establishes the current step's most important fact?
  2. What output would reveal that zip silently stops at the shorter list, so assert equal lengths before scoring?
  3. Can a new user reproduce a threshold evaluator that reports predictions, accuracy, and the confusion counts behind that accuracy from the stated setup?