tensorturnBETA
Home › Machine Learning Tasks

How to Handle Imbalanced Datasets in Machine Learning

To handle an imbalanced dataset, first stop judging the model on accuracy and switch to metrics such as recall, precision, F1 and PR-AUC, then give the rare class more weight with class weights or resampling, and finally tune the decision threshold to match the real cost of each error. Resampling must only touch the training data, never the validation or test sets. TensorTurn shows the class balance of your target in its target analysis as soon as you upload a dataset, and you can ask in plain English for class weights, a stratified split and PR-AUC when it builds the model.

What is an imbalanced dataset?

A dataset is imbalanced when one class is much rarer than the others. Fraud may be 0.5 percent of transactions, a defect 2 percent of parts, churn 10 percent of customers. Mild imbalance (say 60 to 40) rarely needs special treatment. Severe imbalance (below roughly 10 percent for the minority class) changes how you train and, above all, how you evaluate.

The core problem is that most learning algorithms minimise overall error. When one class dominates, the cheapest way to reduce error is to predict the majority class almost always. The model looks accurate and is useless for the thing you care about, which is usually the rare class.

Why accuracy misleads, and which metrics to use

If 99 percent of rows are negative, a model that predicts negative every time scores 99 percent accuracy. Use metrics that focus on the minority class instead.

MetricWhy it helps with imbalanceNotes
Recall (sensitivity)Measures how many real positives you catchPrimary metric when missing a positive is costly
PrecisionMeasures how many flagged rows are real positivesPrimary metric when false alarms are costly or reviews are limited
F1 scoreBalances precision and recall in one numberAssumes both errors matter equally; use F-beta to weight one more
PR-AUC (average precision)Summarises precision and recall across all thresholdsThe best single summary for rare positives; a random model scores the positive rate, not 0.5
ROC-AUCRanking quality across thresholdsCan look optimistic when negatives vastly outnumber positives
Matthews correlation coefficientUses all four confusion matrix cellsStays informative even under heavy imbalance
Balanced accuracyAverage of recall on each classA fairer replacement for plain accuracy

Techniques for imbalanced data compared

TechniqueWhat it doesWhen to use itPitfall
Class weightsMakes errors on the rare class cost more in the loss functionFirst thing to try; supported by logistic regression, random forest, XGBoost, LightGBM and neural networksShifts predicted probabilities, so recalibrate if you need true probabilities
Random undersamplingDrops majority-class rowsVery large datasets where throwing away data is affordableDiscards information; can increase variance
Random oversamplingDuplicates minority-class rowsSmall datasetsEncourages overfitting to the few minority examples
SMOTE and variantsCreates synthetic minority rows by interpolating between neighboursNumeric features with a moderately small minority classCan create unrealistic points, works poorly with categorical features and noisy labels
Threshold tuningMoves the decision cut-off away from 0.5Always; it is cheap and directly targets your business trade-offChoose the threshold on validation data, never on the test set
Focal loss or balanced ensemblesDown-weights easy examples, or trains each model on a balanced subsampleDeep learning (focal loss) or severe imbalance in tabular dataMore complexity to tune and explain

Resample only inside the training data

The most damaging mistake with imbalanced data is resampling before the train and test split. If SMOTE or oversampling runs on the full dataset, synthetic or duplicated minority rows leak into the test set, and the scores you report are inflated. Split first, using a stratified split so each part keeps the original class ratio, then resample only the training fold. With cross-validation, resampling has to happen inside each fold, which is what a pipeline object is for. Your validation and test sets should always reflect the real-world class balance.

Tune the decision threshold to real costs

A classifier outputs a probability. The default rule, positive if above 0.5, is almost never optimal on imbalanced data. Instead, plot precision and recall against the threshold on validation data and pick the point that matches your constraints: the threshold that keeps recall above 90 percent, or the one that flags no more cases than your review team can handle each day. If you can put a cost on a false positive and a false negative, choose the threshold that minimises total expected cost. Threshold tuning often delivers more than any resampling method, and it costs nothing to try.

Other ways to fix imbalance

How to handle imbalanced data on TensorTurn

For complete examples on naturally imbalanced problems, see the fraud detection and credit scoring use cases.

Start building free

Frequently asked questions

What counts as an imbalanced dataset?

There is no strict cut-off, but a minority class below roughly 10 to 20 percent of rows is usually treated as imbalanced, and below 1 percent as severely imbalanced. The more extreme the ratio, the more care you need with metrics and validation.

Is SMOTE better than class weights?

Not reliably. Class weights are simpler, do not create artificial data, and are supported by most algorithms, so they are the usual first choice. SMOTE sometimes helps on small numeric datasets, but it should be compared against class weights on a proper validation set.

Should I balance the test set?

No. The test set should keep the real-world class ratio so that your metrics reflect production performance. Only the training data should be resampled or reweighted.

Why use PR-AUC instead of ROC-AUC for imbalanced data?

ROC-AUC includes the true negative rate, which stays high when negatives vastly outnumber positives, so it can look good even when the model flags many false positives. PR-AUC focuses on precision and recall for the positive class, which is what usually matters.

Does gradient boosting handle imbalance automatically?

Not automatically. XGBoost and LightGBM still optimise overall loss, but they offer parameters such as scale_pos_weight or class weights to give the minority class more influence, and you still need suitable metrics and a tuned threshold.