A machine learning model is only as good as the metric used to evaluate it. Choosing the wrong metric for imbalanced data can mislead you about model performance, even if accuracy looks high.

Understanding Imbalanced Data in Machine Learning

In many real-world datasets, one class occurs far less frequently than the others — fraud detection, disease diagnosis, customer churn, and spam filtering are classic examples. When one class dominates, traditional accuracy becomes misleading: predicting all cases as negative in a 1% positive dataset yields 99% accuracy, yet completely misses the cases that matter.

// THE ACCURACY TRAP
95% of the data is negative. Predicting "negative" for everything gives 95% accuracy — yet zero positives are ever detected. This is why imbalanced datasets require specialised evaluation, not just specialised training.

Quick Recap: Core Metrics

The confusion matrix, precision, recall, and F1-score are covered in full depth in our accuracy vs precision vs recall guide. Here's the condensed version before we move to the metrics this article focuses on.

TP
True Positive
FN
False Negative
FP
False Positive
TN
True Negative
ACCURACY
(TP+TN) / Total

Misleading on imbalanced data

PRECISION
TP / (TP+FP)

Penalises false alarms

RECALL
TP / (TP+FN)

Penalises missed positives

F1-SCORE
2PR / (P+R)

Harmonic balance of both

// increasing precision can reduce recall and vice versa — balancing depends on the application cost. Now let's go beyond these into the metrics that consider both classes simultaneously.

Specificity Balanced Accuracy ROC-AUC G-Mean MCC

Specificity: The Forgotten Half of the Confusion Matrix

While recall measures how well the model finds positives, specificity measures how well it correctly identifies negatives — the majority class performance.

SPECIFICITY TN ÷ (TN + FP)

Specificity is the "recall of the negative class." A model with high specificity rarely raises false alarms on negative cases. It's often called the True Negative Rate, and pairs naturally with recall (the True Positive Rate) since together they describe the full confusion matrix.

// WHEN SPECIFICITY MATTERS
In medical screening, high specificity means healthy patients are correctly cleared, avoiding unnecessary stress, follow-up tests, and costs from false alarms.

Balanced Accuracy: Treating Both Classes Equally

Standard accuracy is dominated by whichever class has more samples. Balanced accuracy fixes this by averaging the performance on each class separately — so a tiny minority class counts just as much as the huge majority class.

BALANCED ACCURACY (Recall + Specificity) ÷ 2
// EXAMPLE — 95/5 imbalanced dataset
RECALL (minority)
0.89

Catches 89% of rare positives

SPECIFICITY (majority)
0.91

Correctly clears 91% of negatives

Balanced Accuracy = (0.89 + 0.91) ÷ 2
= 0.90

// compare this to standard accuracy, which on the same 95/5 split could read 95%+ even with a near-useless minority detector. Balanced accuracy doesn't let the majority class hide a weak model.

ROC Curve & ROC-AUC

The ROC curve (Receiver Operating Characteristic) plots the True Positive Rate (recall) against the False Positive Rate at every possible classification threshold. ROC-AUC is the area under that curve — a single number measuring how well the model separates the two classes across all thresholds.

1.0 0.5 0.0 0.0 0.5 1.0 False Positive Rate True Positive Rate random guess (AUC=0.5) model (AUC=0.93) optimal threshold
0.5 — no skill
0.6–0.7 poor
0.7–0.8 fair
0.8–0.9 good
0.9–1.0 excellent
0.50.70.80.91.0
// THE ROC-AUC TRAP ON IMBALANCED DATA
ROC-AUC can be misleadingly high on heavily imbalanced datasets because the False Positive Rate denominator (TN+FP) is dominated by the huge majority class — making even a mediocre model's FPR look small. This is exactly why the Precision-Recall curve exists.

Precision-Recall Curve (PR Curve)

The PR curve plots precision against recall at every threshold, focusing entirely on minority class performance — it never looks at true negatives at all. PR-AUC is often more informative than ROC-AUC in imbalanced scenarios because it isn't diluted by an easy majority class.

DimensionROC CurvePR Curve
AxesTPR vs FPRPrecision vs Recall
Uses TN?Yes (in FPR)No
Imbalanced dataCan be optimisticMore reliable
Best forBalanced classesRare positive class
Baseline (random)Diagonal (AUC=0.5)Equal to class prevalence

Geometric Mean (G-Mean)

G-Mean balances sensitivity (recall) and specificity using a geometric rather than arithmetic mean — meaning if either score is very low, G-Mean drops sharply, just like F1 does for precision and recall.

G-MEAN √(Recall × Specificity)
// WHY GEOMETRIC, NOT ARITHMETIC
Recall
0.95
×
Specificity
0.10
=
G-Mean
0.31

Arithmetic mean of the same two numbers would be 0.525 — masking the specificity collapse. G-Mean's 0.31 correctly signals a broken model.

Matthews Correlation Coefficient (MCC)

MCC measures the correlation between predicted and actual binary labels, using all four confusion matrix values in one formula. It's widely regarded as one of the most robust single-number metrics for imbalanced datasets because, unlike F1, it doesn't ignore true negatives.

MCC (TP×TN − FP×FN) ÷ √[(TP+FP)(TP+FN)(TN+FP)(TN+FN)]
// MCC RANGES FROM -1 TO +1
your model: 0.62
−1.0 (total disagreement) 0.0 (random) +1.0 (perfect)
// WHY MCC IS ROBUST FOR IMBALANCED DATA
MCC only produces a high score if the model does well on both the majority and minority class simultaneously. A model that just predicts the majority class every time scores close to 0 on MCC — it cannot fake good performance the way accuracy can.

Choosing the Right Metric

RECALL

Priority when missing positives is costly — fraud, disease detection, safety systems.

PRECISION

Priority when false positives are costly — spam filters, content moderation, legal flags.

F1-SCORE

When both error types matter and you need one balanced number to optimise.

PR-AUC

Best for probabilistic predictions on imbalanced data — threshold-independent view of minority performance.

MCC

When you want one number that's hard to game and accounts for all four confusion matrix cells.

Common Beginner Mistakes

Relying only on accuracy. It hides minority class failure completely on imbalanced data.

Ignoring class imbalance entirely. Always check class distribution before choosing a metric or model.

Using ROC-AUC blindly. It can look optimistic on heavily skewed data — pair it with PR-AUC.

Neglecting the real-world cost of errors. A false negative in cancer screening is not equivalent to a false positive in spam filtering — let the metric reflect that.

Practical Tips

  • Always inspect the confusion matrix directly, not just summary scores
  • Use PR curves for probability outputs on imbalanced data
  • Combine multiple metrics for a complete evaluation — no single number tells the whole story
  • Use classification_report() from scikit-learn for quick, complete summaries
  • Resampling techniques like oversampling or undersampling are applied during training, not evaluation — always evaluate on the original distribution

Python Examples

A complete example using scikit-learn to calculate every metric covered above, plus ROC and PR curves:

imbalanced_metrics.py
from sklearn.metrics import (
    balanced_accuracy_score,
    roc_auc_score, average_precision_score,
    matthews_corrcoef, confusion_matrix,
    classification_report, roc_curve, precision_recall_curve
)
import numpy as np

# ── Predictions & probabilities ──────────────────────────
y_true  = [1,0,1,1,0,0,0,0,1,0]
y_pred  = [1,0,1,0,0,1,0,0,1,0]
y_proba = [0.91,0.12,0.83,0.44,0.20,0.61,0.18,0.09,0.77,0.15]

# ── Confusion matrix → TN, FP, FN, TP ────────────────────
tn, fp, fn, tp = confusion_matrix(y_true, y_pred).ravel()

# ── Specificity (not built into sklearn directly) ────────
specificity = tn / (tn + fp)
print(f"Specificity      : {specificity:.4f}")

# ── Balanced accuracy ─────────────────────────────────────
print(f"Balanced Accuracy: {balanced_accuracy_score(y_true, y_pred):.4f}")

# ── ROC-AUC & PR-AUC ──────────────────────────────────────
print(f"ROC-AUC          : {roc_auc_score(y_true, y_proba):.4f}")
print(f"PR-AUC           : {average_precision_score(y_true, y_proba):.4f}")

# ── G-Mean (manual — not built into sklearn) ─────────────
recall     = tp / (tp + fn)
g_mean     = np.sqrt(recall * specificity)
print(f"G-Mean           : {g_mean:.4f}")

# ── Matthews Correlation Coefficient ─────────────────────
print(f"MCC              : {matthews_corrcoef(y_true, y_pred):.4f}")

# ── Full report ───────────────────────────────────────────
print("\n" + classification_report(y_true, y_pred))

# ── ROC & PR curve points (for plotting) ─────────────────
fpr, tpr, _        = roc_curve(y_true, y_proba)
prec_arr, rec_arr, _ = precision_recall_curve(y_true, y_proba)

// note: specificity and g_mean aren't built-in sklearn functions — you compute them from the confusion matrix directly, as shown above.

Practice the Concepts

💻

GitHub Repository: Imbalanced Data Evaluation Metrics

All Python code and datasets used in this article are available to clone and run yourself, including the ROC and PR curve plotting scripts.

Explore on GitHub →

FAQs

Why is accuracy not a good metric for imbalanced data?

Accuracy can be misleading when one class heavily dominates the dataset. A model may achieve high accuracy by always predicting the majority class while completely failing to detect the minority class.

What is the best evaluation metric for imbalanced datasets?

There is no single "best" metric. Precision, recall, and F1-score are commonly used depending on whether false positives or false negatives matter more in your problem. For a single robust number, MCC or PR-AUC are strong choices.

When should I use precision instead of recall?

Use precision when false positives are costly, such as in spam detection where incorrectly marking a legitimate email as spam is undesirable.

When is recall more important than precision?

Recall is more important when missing positive cases is costly, such as in fraud detection or medical diagnosis.

What is the difference between ROC curve and Precision-Recall curve?

ROC curves work well for balanced datasets, while Precision-Recall curves are more informative for imbalanced datasets because they focus on minority class performance and don't involve true negatives.

Is F1-score better than accuracy for imbalanced data?

Yes, F1-score balances precision and recall, making it far more informative than accuracy when dealing with imbalanced class distributions.

Do I need special datasets to evaluate imbalanced data?

No. Any dataset can be imbalanced. However, using stratified train-test splits helps ensure proper, representative evaluation.

Should I resample data before evaluating metrics?

No. Resampling techniques like oversampling or undersampling are applied during training, not evaluation. Always evaluate on the original, unmodified distribution to get an honest picture of real-world performance.

Summary & Key Takeaways

  • Accuracy is misleading for imbalanced datasets — it hides minority class failure
  • Precision, Recall, F1-Score, and PR-AUC are essential everyday metrics
  • ROC curves can be misleading in heavily imbalanced cases — pair with PR-AUC
  • Specificity and Balanced Accuracy give equal weight to both classes
  • G-Mean and MCC are robust single-number metrics that are hard to game
  • Always align metric choice with the real-world cost of each error type

For the practical training-side techniques that pair with these evaluation metrics — resampling, SMOTE, class weighting, and ensemble methods — see our companion guide on handling imbalanced datasets in machine learning.

Khalid Hussain

Founder of Review Publically. Writes hands-on guides on data science, machine learning and AI tools, testing every model and library before recommending it.