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.
| Metric | Why it helps with imbalance | Notes |
|---|---|---|
| Recall (sensitivity) | Measures how many real positives you catch | Primary metric when missing a positive is costly |
| Precision | Measures how many flagged rows are real positives | Primary metric when false alarms are costly or reviews are limited |
| F1 score | Balances precision and recall in one number | Assumes both errors matter equally; use F-beta to weight one more |
| PR-AUC (average precision) | Summarises precision and recall across all thresholds | The best single summary for rare positives; a random model scores the positive rate, not 0.5 |
| ROC-AUC | Ranking quality across thresholds | Can look optimistic when negatives vastly outnumber positives |
| Matthews correlation coefficient | Uses all four confusion matrix cells | Stays informative even under heavy imbalance |
| Balanced accuracy | Average of recall on each class | A fairer replacement for plain accuracy |
Techniques for imbalanced data compared
| Technique | What it does | When to use it | Pitfall |
|---|---|---|---|
| Class weights | Makes errors on the rare class cost more in the loss function | First thing to try; supported by logistic regression, random forest, XGBoost, LightGBM and neural networks | Shifts predicted probabilities, so recalibrate if you need true probabilities |
| Random undersampling | Drops majority-class rows | Very large datasets where throwing away data is affordable | Discards information; can increase variance |
| Random oversampling | Duplicates minority-class rows | Small datasets | Encourages overfitting to the few minority examples |
| SMOTE and variants | Creates synthetic minority rows by interpolating between neighbours | Numeric features with a moderately small minority class | Can create unrealistic points, works poorly with categorical features and noisy labels |
| Threshold tuning | Moves the decision cut-off away from 0.5 | Always; it is cheap and directly targets your business trade-off | Choose the threshold on validation data, never on the test set |
| Focal loss or balanced ensembles | Down-weights easy examples, or trains each model on a balanced subsample | Deep learning (focal loss) or severe imbalance in tabular data | More 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
- Collect more minority examples, which beats every algorithmic trick when it is possible.
- Check label quality: in rare classes, a handful of mislabeled rows is a large share of the signal.
- Engineer features that specifically describe rare behaviour, such as unusual amounts or new devices in fraud data.
- When positives are extremely rare and poorly defined, consider framing the problem as anomaly detection instead.
How to handle imbalanced data on TensorTurn
- Upload your dataset and choose the target column. Target analysis shows the class balance immediately, so you know how rare the minority class is before you train anything.
- Review the leakage flags in target analysis. On imbalanced problems a leaky feature can make a weak model look perfect.
- Describe the model in chat, for example: predict is_fraud with XGBoost, use a stratified split, apply class weights, report PR-AUC, recall and the confusion matrix, and pick the threshold that keeps precision above 0.5.
- TensorTurn generates and runs the notebook. You can ask for resampling inside the training data only, compare it against class weights, or change the threshold, all in plain English or by editing cells.
- Deploy the model as an authenticated /predict endpoint and apply your chosen threshold to the returned probability.
For complete examples on naturally imbalanced problems, see the fraud detection and credit scoring use cases.
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.