Class Imbalance: When Rare Conditions Dominate Your Research Question
Why most clinical datasets have far more normal cases than pathological ones, and strategies for handling this imbalance without introducing bias.
In a screening mammography program, about five women in every thousand screened have cancer. A model that reports "no cancer" for every single mammogram is therefore 99.5% accurate. It is also useless.
This probably seems obvious and elementary, but it's pretty common in the medical literature, albeit in more subtle forms. The conditions for which it is worth building a detector are mostly rare: the pneumothorax among routine chest films, the large-vessel occlusion among head CTs, the sepsis among admissions. Class imbalance is the normal state of clinical data.
What imbalance does to training
Training adjusts the model to reduce its average error over the training cases. When 99% of those cases are negative, the fastest way to a low average error is to get the negatives right, and the positives barely register. The extreme outcome is a model that predicts the majority class every time. The usual outcome is milder: a model that has learned something about the positive class but is reluctant to call it, with scores bunched near zero.
Imbalance as a ratio is less of a problem than the absolute number of positive cases. A dataset with 5,000 positives and 495,000 negatives is at 1% and will train a good model, because 5,000 examples are enough to learn what the disease looks like. A dataset with 50 positives and 4,950 negatives is at the same 1% and is in trouble, and the trouble is the 50. No resampling trick will increase the amount of information that the 50 examples already hold.
What imbalance does to evaluation
Accuracy stops meaning anything, as the mammography example shows. Instead we typically report sensitivity and specificity, which are each computed within one class and so are unaffected by the mix (see 4.1 Classification Metrics).
The ROC curve and its AUC are built from sensitivity and specificity, so they are also unaffected by prevalence. That sounds like (and is) a good thing, but there's a catch: we can wind up with an AUC of 0.95 for both a 50% prevalence and a 0.5% prevalence, but the 0.5% prevalence has the possibility of a very low predicive value - maybe in the single digits. Takaya Saito and Marc Rehmsmeier argued in a 2015 paper that for imbalanced data the precision-recall curve is the more informative plot, because precision (the same thing as positive predictive value) falls as the positive class gets rarer and the curve shows it. The point is to understand the underlying mechanisms of the metrics so you know when to verify with other measures.
The small absolute number of positives also makes the estimates shakier. If your test set has 2,000 cases and 20 positives, your sensitivity is a fraction of 20, and the error bars will make you use up all the ink in your printer. Maker sure to count the positives in the test set, not the cases (see 2.2 How Much Data Do You Need?).
Remedy one: get more positives
The best fix is more real examples of the rare class. Search the archive by diagnosis code, pathology result or report text and pull every positive you can find, then sample negatives to go with them. Add sites. Extend the date range.
This is called enrichment, and it's very common. It has a couple caveats though.
The first is that the positives and negatives now arrived by different routes. Positives found through the pathology database were all worked up; negatives sampled from routine imaging were not. If the positives come from a different period, scanner or department than the negatives, the model has a shortcut available (see 2.1 Why Data Quality Matters More Than Model Complexity). Sample the negatives from the same sites, scanners and years as the positives. Include the difficult negatives as well, the patients who were suspected of the disease and turned out not to have it.
The second is that the model's probabilities are now wrong for the real world, which we'll address below.
Remedy two: adjust the training
If you can't get more positives, you can try to get more out of the ones you have.
Oversampling shows the model each positive case several times per pass through the data. Undersampling discards most of the negatives. Oversampling risks memorizing the few positives; undersampling throws away information about what normal looks like, which is often the more varied class. In imaging, oversampling is usually combined with augmentation, so that the repeated positives are at least rotated and shifted copies (see 2.5 Data Preprocessing and Augmentation).
Class weighting leaves the data alone and changes the arithmetic, so that an error on a positive case costs, say, twenty times as much as an error on a negative. The effect is much the same as oversampling.
Focal loss, introduced by Tsung-Yi Lin and colleagues in 2017 for object detection, turns down the contribution of cases the model already gets right easily, so that training concentrates on the hard ones. It is widely used for detection tasks where almost every candidate location is background.
SMOTE, from a 2002 paper by Nitesh Chawla and colleagues, manufactures new minority cases by interpolating between existing ones. It was designed for tabular data. Interpolating between two patients' lab values gives a plausible patient. Interpolating between two CT scans gives a double exposure, so it is not used on images.
Your engineers will (hopefully) know all of these. What you should know is that they all do roughly the same thing: they push the model toward calling the positive class more readily. That can help a deep network learn features of the rare class that it would otherwise ignore. It doesn't add information, and it has the same side effect as enrichment.
Probabilities are now too high
Regardless of whether you use enrichment or resampling, your training will see a world where half (or 35%, or whatever) of cases are positive. Its output scores assume a 50% prior, and when it leaves your lab and sees a world where 1% are positive, every probability it reports will be too high.
The ranking of cases is unaffected, so sensitivity, specificity and AUC should hold up. What breaks is calibration: the correspondence between "the model says 90%" and "90% of such cases are positive" (see 4.4 Calibration).
Don't panic, it turns out we can correct for this. The size of the distortion is easy to work out, because prevalence acts on the odds. Take a model trained at 50% prevalence and used at 1%. A score of 0.90 is odds of 9 to 1. The prevalence odds have gone from 1 to 1 down to 1 to 99, so the corrected odds are 9 to 99, which is a probability of about 8%. The case the model called 90% likely is 8% likely.
Ruben van den Goorbergh and colleagues tested this on clinical risk prediction in a 2022 paper bluntly titled "The harm of class imbalance corrections for risk prediction models." Random oversampling, random undersampling and SMOTE all produced models that badly overestimated risk, and none improved discrimination over simply fitting the model to the imbalanced data. Their advice for risk models was to leave the imbalance alone and choose the decision threshold deliberately.
So there are two rules. If you rebalance, recalibrate afterwards on data at the real prevalence, or apply the odds correction above. And if the model's output is going to be read as a probability, as in a risk score, don't treat rebalancing lightly, it's a serious part of your method.
Deciding on a threshold
A classifier produces a score, usually between 0 and 1. Turning the score into "positive" or "negative" just means assigning a threshold. With rare disease, sensible thresholds are often far below 0.5.
Choosing it is a clinical judgment about the relative cost of a miss and a false alarm. For a triage tool that reorders a worklist, a false positive costs a radiologist a few seconds, and you can set the threshold low to catch nearly everything. For a tool that sends patients to biopsy, the situation is different.
We bring this up because a lot of what is assumed to be and imbalance problem is actually a threshold problem. A model that "misses all the positives" at 0.5 may separate them perfectly well at 0.1. Look at the full ROC and precision-recall curves before concluding that the training needs fixing. (And choose the threshold on the validation set, never the test set.) (see 3.2 Training, Validation, and Test Sets).
Keep the test set pure
Whatever you do to the training data, the test set's job is to tell you what will happen in use.
The cleanest test set is a random sample from the intended population, at its natural prevalence. Then every metric, predictive values included, should be pretty good. The cost is test set size: at 1% prevalence, 150 positives means 15,000 cases.
The usual compromise is an enriched test set. That works if you report the enrichment, report sensitivity and specificity (which survive it), and compute predictive values for the real prevalence using Bayes' rule instead of reading them off the enriched sample.
When you split the data, stratify, so that each of the training, validation and test sets gets its share of positives. With few positives a purely random split can leave the test set with a handful or none just by bad luck.
Imbalance inside the image
Segmentation has its own version of the rare-prevalence disorder. A small lesion may occupy a hundredth of a percent of the voxels in a scan, so a model that labels everything "background" is 99.99% right per voxel.
The standard answer is to train with a loss based on the Dice coefficient, which measures overlap with the lesion and ignores the vast correct background. Fausto Milletari and colleagues introduced this in their 2016 V-Net paper, and it or a combination of it with other losses is now the default. Engineers also sample training patches so that a good share of them contain some lesion.
Evaluation has the same trap. Averaged over all voxels, or dominated by a few large lesions, a segmentation score can hide the fact that the small lesions were all missed. Calculate per-lesion detection rates as well (see 4.3 Segmentation Metrics).
Key takeaways
- With rare conditions, accuracy is meaningless. A model that always says "normal" scores near 100%.
- The absolute number of positive cases counts for more than the ratio. No resampling method adds information.
- The best remedy is more real positives, with negatives drawn from the same sites, scanners and period, including the hard negatives.
- Oversampling, undersampling, class weights and focal loss all push the model toward the rare class. They can help a network learn, and they inflate its probabilities.
- A model trained on balanced data overestimates risk at real prevalence. Recalibrate, and for risk scores consider not rebalancing.
- The decision threshold is a separate, clinical choice, and 0.5 is rarely right for rare disease.
- Test at natural prevalence if you can. If the test set is enriched, say so and recompute predictive values for the real prevalence.
- Report sensitivity, specificity and a precision-recall curve, with the count of positives in the test set.
What to read next
- 2.5 Data Preprocessing and Augmentation: getting more out of the positives you have
- 2.8 Synthetic Data and Data Simulation: generating examples of the rare class, with caveats
- 4.1 Classification Metrics: Sensitivity, Specificity, and Beyond: the metrics that survive imbalance
- 4.4 Calibration: Does a 90% Confidence Score Really Mean 90%?: measuring and repairing probabilities
- 7.2 Demographic Fairness: Performance Across Populations: imbalance between patient groups
This article is part of the AI in Clinical Research Knowledge Base.