SeeingML
How Machines Learn Guide 6 of 6 · tap to switch
✦ Interactive Visual Guide 9 min · 4 hands-on labs · Beginner friendly

Precision, Recall, F1 Score & Imbalanced Data

Why 99% accuracy can hide a totally broken model, how Precision, Recall, F1, and PR curves expose the truth, and what fixes actually work.

Suppose a hospital builds an AI tool to scan 1,000 routine checkups for a rare early-stage tumor. Out of every 1,000 patients, 990 are healthy and only 10 actually need urgent care (1%).

An engineer excitedly walks into the meeting and announces: “Our model hit 99.0% accuracy!”

Sounds incredible, until you peek inside the code and discover the model ignores the scan completely and outputs “Healthy” for every single person who walks through the door.

When one outcome is much rarer than the other, you are dealing with imbalanced data, and plain accuracy can disguise total failure. Try toggling between Lazy Model and Real Screening Model across different rarity levels below to feel the Accuracy Paradox firsthand.

Interactive Lab 1: The 99% Accuracy Paradox (1,000 Clinic Scans)
How rare is the disease in this clinic?
Each tile = 10 patients (100 tiles = 1,000 scans)
Sick caughtSick missedHealthy false alarmHealthy cleared
Headline Accuracy
99.0%
990 / 1,000 right overall
Sick Patients Caught
0 / 10 (0%)
Missed sick patients: 10
False Alarms on Healthy Patients
0
Healthy scans flagged for recheck
Real Hits Among Alarms
No alarms
Model never flags anyone
The Accuracy Paradox in action! This lazy model guesses "Healthy" for every single patient without looking at the scan. Because 99% of patients are healthy, it brags 99.0% accuracy while missing ALL 10 sick patients (0% caught). Click "Real Screening Model" above to compare!

On imbalanced problems (cancer screening, credit card fraud, jet engine failure, spam detection), plain accuracy is a vanity metric. A genuinely helpful model that catches 8 of 10 sick patients while flagging a few dozen healthy scans for a double-check can actually show lower headline accuracy than a broken rubber stamp!


Precision vs. Recall, F1 Score & the Confusion Matrix

Instead of mashing every right and wrong guess into one misleading accuracy percentage, sort all four possible outcomes into a simple 2x2 table called a Confusion Matrix:

  • True Positives (TP): Sick patients we caught.
  • False Negatives (FN): Sick patients we missed (dangerous in medicine!).
  • False Positives (FP): Healthy patients we alarmed unnecessarily (costly follow-ups, or important emails sent to spam!).
  • True Negatives (TN): Healthy patients we cleared cleanly.

From those four boxes come the three metrics real ML teams actually monitor:

  1. Precision: Out of everyone we flagged, how many were truly sick? (Measures how trustworthy your alarms are.)
  2. Recall: Out of all truly sick patients, how many did we actually catch? (Measures how few real cases slipped past.)
  3. F1 Score: A strict combined grade that crashes toward 0% if either Precision or Recall is awful (in math, this is called a harmonic mean). Unlike a regular average, it refuses to give a passing score to a lazy model that aces one number while failing the other.

Grab the amber Cut handle below and slide it left and right, or try the three clinic presets, to watch Precision and Recall trade places in real time.

Interactive Lab 2: Drag the Cutoff & Watch the Confusion Matrix
Curves drawn same height to show overlap · Healthy group is 9× larger (900 vs. 100)← Cleared as HealthyFlagged as Sick →Patients0%25%50%75%100%Model Predicted Risk Score (100 Sick vs. 900 Healthy Patients)Healthy Scores (900)Sick Scores (100)↔ Cut 50%
True Positive (Caught)
84
Sick & flagged
False Negative (Missed!)
16
Sick but sent home
False Positive (Alarm)
76
Healthy but flagged
True Negative (Cleared)
824
Healthy & cleared
Precision (Of those flagged, how many were truly sick?)53%
Recall (Of all truly sick patients, how many did we catch?)84%
F1 Score (Strict combined grade of both)65%
50%
Balanced clinic cutoff (50%): Precision is 53%, Recall is 84%, and their strict combined grade (F1 Score) reaches 65%. Drag the amber Cut handle left or right to watch them trade places.

Why ROC curves can disguise rare-event failure (ROC vs. PR)

So far, we inspected one alarm cutoff at a time. To compare models across every possible cutoff from 0% to 100% at once, teams sweep the alarm cutoff from one end to the other and trace a curve showing every trade-off the model can make.

The classic version is the ROC curve (Receiver Operating Characteristic), summarized by its AUC (Area Under the Curve), a single score from 0.50 (a random coin flip) up to 1.00 (perfect separation). Its vertical axis is True Positive Rate, which is simply Recall (the share of sick patients caught), while its horizontal axis is False Positive Rate, which divides false alarms by all healthy patients.

Here is the trap that catches even experienced practitioners: when you have 990 healthy patients, creating 50 false alarms only nudges False Positive Rate up by 50 / 990 = 0.05, so the ROC curve barely flinches!

Click 50% Balanced and then 1% Rare below to watch the exact same model’s ROC-AUC stay frozen while its Precision-Recall curve drops sharply to tell the honest story.

Interactive Lab 3: Why ROC Looks Rosy While PR Tells the Truth
How rare sick patients are:
ROC Curve (Unchanged!)ROC-AUC: 0.93
0.00.00.50.51.01.0Sick Caught (Recall)False Alarms / All Healthy (FPR)Coin flip = 0.5050% cutoff
Precision-Recall Curve (Honest)PR-AUC: 0.94
0.00.00.50.51.01.0Alarm Accuracy (Precision)Sick Caught (Recall)No-skill baseline (50%)50% cutoff
At 50% alarm cutoff: 421 / 500 sick caught · 42 / 500 healthy falsely alarmed
Alarm Accuracy (Precision): 91%
On a balanced 50/50 clinic, BOTH curves look rosy (ROC-AUC 0.93, PR-AUC 0.94). Now click "1% Rare" above to watch what happens to the exact same model when sick patients become rare!

That contrast explains why the Precision-Recall curve (PR-AUC) is the gold standard for rare-event detection: Precision compares true catches directly against false alarms (TP / (TP + FP)), so huge healthy populations can never hide a noisy alarm system.


Three real fixes for imbalanced data (and one sneaky leak)

Once you are measuring the right metric, how do you actually improve rare-class detection without ruining your model’s honesty? Most teams try three practical levers, in this order:

  1. Threshold Tuning (Move the Alarm Cutoff): Leave training untouched so the model’s risk percentages stay realistic, then slide the decision cutoff lower (for example, from 50% down to 15%) so doctors catch more rare cases.
  2. Class Weights (Extra Mistake Penalties): During training, tell the model that missing one rare sick patient counts as a much bigger mistake (such as 10x heavier) than a false alarm on a healthy patient. This nudges the model to pay close attention to rare patterns without inventing fake data.
  3. Oversampling and SMOTE (Making Extra Rare Examples): Oversampling adds extra copies of rare examples during training so the rare class is harder to ignore. The most famous method is SMOTE (Synthetic Minority Oversampling), which picks neighboring rare sick patients and creates blended synthetic copies in between them.

Watch out for one sneaky trap with SMOTE: if you generate synthetic copies on your entire dataset before splitting into training and validation sets, near-identical clones of the same rare patient end up in both groups. Your model then scores a fake, sky-high validation grade because it is tested on clones of patients it already practiced on, only to fail on brand-new patients later. Always run SMOTE strictly inside your training split!

Compare all three fixes below, and on Tab 3 toggle between Broken: SMOTE Before Split and Safe: SMOTE Inside Training Only to see that oversampling leak happen visually.

Interactive Lab 4: Comparing Real Imbalance Fixes (1% Rare Clinic)
Risk Scores: Honest (unchanged risk scores)
Leave training untouched · Slide the alarm cutoff left from 50% to 15%Old 50% cutoffNew 15% cutoffSlide cutoff leftNewly caught sick patientsRisk % stays honest0%15%50%100%
Recall (Sick Caught)
86%
Precision (Alarm Accuracy)
24%
Validation F1 Score
38%
How it works: Try this first! Leave training untouched so the model's risk percentages stay realistic, then slide the alarm cutoff lower (for example, from 50% down to 15%) so doctors catch more rare cases.
Watch out: Choose your alarm cutoff using your validation split, never your sealed test vault.
Best first step! Lowering the alarm cutoff from 50% to 15% lifts Recall to 86% and F1 to 38% while keeping every predicted risk percentage honest.
See exact formulas, Bayes-optimal thresholds & academic citationsThesis / Reference

1. Precision, Recall, and the FβF_\beta Family:

Precision=TPTP+FP,Recall=TPTP+FN\text{Precision} = \frac{\text{TP}}{\text{TP} + \text{FP}}, \qquad \text{Recall} = \frac{\text{TP}}{\text{TP} + \text{FN}}
Fβ=(1+β2) Precision⋅Recallβ2⋅Precision+Recall,F1=2⋅Precision⋅RecallPrecision+RecallF_\beta = (1 + \beta^2)\,\frac{\text{Precision} \cdot \text{Recall}}{\beta^2 \cdot \text{Precision} + \text{Recall}}, \qquad F_1 = \frac{2 \cdot \text{Precision} \cdot \text{Recall}}{\text{Precision} + \text{Recall}}

Setting β=2\beta = 2 (F2F_2) weights Recall twice as heavily as Precision (medical screening); setting β=0.5\beta = 0.5 weights Precision twice as heavily (spam / content moderation).

2. Bayes-Optimal Cost-Sensitive Threshold (Elkan, 2001): If a classifier outputs calibrated posterior probabilities p^=P(Y=1∣x)\hat{p} = P(Y=1 \mid \mathbf{x}), and a False Positive costs CFPC_{\text{FP}} while a False Negative costs CFNC_{\text{FN}}, expected cost is minimized strictly at:

τ∗=CFPCFP+CFN\tau^* = \frac{C_{\text{FP}}}{C_{\text{FP}} + C_{\text{FN}}}

For example, if missing a malignant tumor is 19× costlier than a follow-up biopsy, the optimal decision threshold is τ∗=11+19=0.05\tau^* = \frac{1}{1+19} = 0.05, requiring zero distortion of training class priors!

3. ROC-AUC vs. PR-AUC & Matthews Correlation Coefficient (MCC): As demonstrated by Saito & Rehmsmeier (2015, PLOS ONE), ROC-AUC is invariant to class prevalence whereas PR-AUC reflects the real-world precision drop under severe skew. When you need a single symmetric summary across all four confusion quadrants, Matthews Correlation Coefficient (MCC) (Chicco & Jurman, 2020) remains strictly honest even at 99:1 skew:

MCC=TP⋅TN−FP⋅FN(TP+FP)(TP+FN)(TN+FP)(TN+FN)\text{MCC} = \frac{\text{TP}\cdot\text{TN} - \text{FP}\cdot\text{FN}}{\sqrt{(\text{TP}+\text{FP})(\text{TP}+\text{FN})(\text{TN}+\text{FP})(\text{TN}+\text{FN})}}

4. Caution on Resampling / SMOTE (Chawla et al., 2002): Artificially balancing training classes via SMOTE shifts the learned log-odds intercept by ln⁡ ⁣(πresampled(1−πtrue)πtrue(1−πresampled))\ln\!\left(\frac{\pi_{\text{resampled}}(1-\pi_{\text{true}})}{\pi_{\text{true}}(1-\pi_{\text{resampled}})}\right), miscalibrating raw probabilities unless recalibrated afterward (see van den Goorbergh et al., 2022, JAMIA). Always benchmark plain threshold tuning first.

See PR-AUC, class weights & threshold tuning in PythonOptional Code
python
from sklearn.linear_model import LogisticRegression
from sklearn.metrics import average_precision_score, precision_recall_curve, classification_report
import numpy as np

# Option A: Keep honest probabilities, then pick threshold on validation set
model = LogisticRegression()
model.fit(X_train, y_train)
probs = model.predict_proba(X_val)[:, 1]

print("PR-AUC (Average Precision):", round(average_precision_score(y_val, probs), 3))

# Pick the threshold that maximizes F1 on validation
prec, rec, thresholds = precision_recall_curve(y_val, probs)
f1_scores = 2 * prec[:-1] * rec[:-1] / np.maximum(prec[:-1] + rec[:-1], 1e-9)
best_t = thresholds[np.argmax(f1_scores)]

preds = (probs >= best_t).astype(int)
print(f"Best validation threshold: {best_t:.2f}")
print(classification_report(y_val, preds, digits=3))

Congratulations: you just completed Path 01!

Across How Machines Learn, you went from drawing your first prediction line on London homes to classifying bank fraud with sigmoid probabilities, locking test vaults against leakage, diagnosing bias vs. variance, running K-fold cross-validation, and seeing right through the 99% Accuracy Paradox.

Ready for Path 02: Working With Data? Jump into Descriptive Statistics or browse the full Visual Library.

✓ Self-Check

Quick Intuition Check

Four quick real-world scenarios. No scores, just test your intuition.

1

Only 0.5% of transactions on a payment network are fraudulent. A new model reports 99.5% accuracy on the test set. What should you check first?

Pick an option first, or peek anytime
2

An email spam filter catches 95% of spam messages (high Recall), yet 40% of the emails it dumps into the spam folder are actually important bills and job offers. Which metric is suffering?

Pick an option first, or peek anytime
3

Why is the Precision-Recall curve usually preferred over the ROC curve when only 1% of cases are rare positives (like sick patients or fraud)?

Pick an option first, or peek anytime
4

Applying SMOTE oversampling to your entire dataset before splitting into training and validation sets is a safe way to boost rare-class F1 scores.

Pick an option first, or peek anytime
Quick Reference

Common Questions

What is precision and recall in machine learning?
Precision asks: of all the items your model flagged as positive, how many were truly positive (TP / (TP + FP))? Recall asks: of all the real positives that existed, how many did your model catch (TP / (TP + FN))? Raising the alarm threshold boosts precision while lowering recall, and lowering it does the reverse.
What is the difference between accuracy, precision, recall, and F1 score?
Accuracy measures overall correct predictions, which becomes misleading on rare events (predicting 'no fraud' every time gets 99% accuracy while catching zero fraud). Precision measures alarm reliability, recall measures how many real cases you catch, and F1 score is their harmonic mean, rewarding models only when both precision and recall stay strong.
What is the Accuracy Paradox in machine learning?
The Accuracy Paradox happens on imbalanced datasets when a trivial model that always predicts the majority class gets a high accuracy score (such as 99% when 1% of rows are fraud or disease) despite catching zero real positive cases.
What is the difference between Precision and Recall?
Precision asks: out of every case the model flagged, how many were genuinely positive? Recall asks: out of all genuinely positive cases that existed, how many did the model catch? Raising the threshold boosts Precision; lowering it boosts Recall.
What does F1-Score measure?
F1-Score is the harmonic mean of Precision and Recall. Unlike a simple average, the harmonic mean collapses toward zero if either Precision or Recall is terrible, making it impossible to cheat by flagging everything or flagging nothing.
Should I use ROC-AUC or PR-AUC for imbalanced data?
Prefer the Precision-Recall curve (PR-AUC / Average Precision) when the positive class is rare (for example, under 5%). ROC curves divide false alarms by the huge pool of healthy negatives, making a flood of false positives look tiny.
Should I always use SMOTE on imbalanced datasets?
No. Start with threshold tuning and well-calibrated probabilities first, then test class weights. If you try SMOTE or oversampling, apply it strictly inside training folds (never before splitting) and check whether probability calibration got distorted.

Written & illustrated by Muhammad Aashir Irshad · Updated December 2026 · Free open-access reference

https://seeingml.com/learn/imbalanced-data/ Open GitHub issue Suggest an edit
Cite this guide in a paper, thesis, or course (BibTeX & APA)
BibTeX
@misc{irshad2026imbalanceddata,
  author       = {Irshad, Muhammad Aashir},
  title        = {Precision, Recall, F1 Score & Imbalanced Data: Interactive Visual Guide},
  howpublished = {SeeingML},
  year         = {2026},
  month        = {dec},
  url          = {https://seeingml.com/learn/imbalanced-data/},
  note         = {Interactive visual guide}
}
APA

Irshad, M. A. (2026). Precision, Recall, F1 Score & Imbalanced Data: Interactive Visual Guide. SeeingML. https://seeingml.com/learn/imbalanced-data/