How Machines Learn Guide 6 of 6 · tap to switch
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.
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:
- Precision: Out of everyone we flagged, how many were truly sick? (Measures how trustworthy your alarms are.)
- Recall: Out of all truly sick patients, how many did we actually catch? (Measures how few real cases slipped past.)
- 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.
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.
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:
- 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 to15%) so doctors catch more rare cases. - 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.
- 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.
See exact formulas, Bayes-optimal thresholds & academic citationsThesis / Reference
1. Precision, Recall, and the Family:
Setting () weights Recall twice as heavily as Precision (medical screening); setting weights Precision twice as heavily (spam / content moderation).
2. Bayes-Optimal Cost-Sensitive Threshold (Elkan, 2001): If a classifier outputs calibrated posterior probabilities , and a False Positive costs while a False Negative costs , expected cost is minimized strictly at:
For example, if missing a malignant tumor is 19× costlier than a follow-up biopsy, the optimal decision threshold is , 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:
4. Caution on Resampling / SMOTE (Chawla et al., 2002): Artificially balancing training classes via SMOTE shifts the learned log-odds intercept by , 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
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.
Quick Intuition Check
Four quick real-world scenarios. No scores, just test your intuition.
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?
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?
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)?
Applying SMOTE oversampling to your entire dataset before splitting into training and validation sets is a safe way to boost rare-class F1 scores.
Common Questions
What is precision and recall in machine learning?
What is the difference between accuracy, precision, recall, and F1 score?
What is the Accuracy Paradox in machine learning?
What is the difference between Precision and Recall?
What does F1-Score measure?
Should I use ROC-AUC or PR-AUC for imbalanced data?
Should I always use SMOTE on imbalanced datasets?
Related Visual Guides
Logistic Regression
How a machine turns clues into clean 0% to 100% probabilities and makes yes/no decisions, from spam filters to bank fraud alerts.
Cross-Validation & K-Fold Cross-Validation
How rotating every slice of your dataset through the exam seat turns lucky split roulette into a trustworthy score.
Decision Trees & Split Impurity
Turn messy tables into crystal-clear flowcharts of yes/no questions, understand Gini Impurity vs. Entropy, and see why pruning stops overfitted boxes.
Written & illustrated by Muhammad Aashir Irshad · Updated December 2026 · Free open-access reference
Cite this guide in a paper, thesis, or course (BibTeX & APA)
@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}
} Irshad, M. A. (2026). Precision, Recall, F1 Score & Imbalanced Data: Interactive Visual Guide. SeeingML. https://seeingml.com/learn/imbalanced-data/