How Do You Handle Class Imbalance?
Why a rare outcome fools a model, and how class weights, resampling, the decision threshold and the right metrics fix it, for your AI interview.
In short
When one outcome is rare, a model can score high on accuracy and still miss it. Fix it with class weights or resampling during training, move the decision threshold, and judge the model on recall and precision.
12 min readIntermediateCommon · estimateFacts checked 27 November 2026
Say it out loud
Read it once, then say it without looking. Start with the short one; use the long one when they ask you to go deeper.
Class imbalance means one outcome is much rarer than the other, like fraud in card payments. A model can be 99 percent accurate by always saying legit, and still miss every fraud. So I weight the rare class more during training, or resample the rows, then tune the decision threshold on held-out data. I judge the model on recall and precision, because they show how much fraud it catches and how many false alarms it raises.
Class imbalance means one label is far more common than the other. In card payments, fraud can be less than 0.1 percent of the rows. Real data is usually like this, and the common label is the majority class while the rare one is the minority class.
The trouble is that a model can look good while failing. If 99.9 percent of payments are fine, a model that approves everything is 99.9 percent accurate and catches no fraud. Training also sees too few rare examples to learn them well, so the rare class gets little attention.
The fixes work at three points. Class weights make each rare example count more in the loss, which is the number training tries to reduce. Resampling changes the rows the model sees, by keeping more rare rows or fewer common ones. Then the decision threshold can move, so the model flags a payment above a cut-off I pick on held-out data.
I measure with recall, the share of real fraud I catch, and precision, the share of flags that are real. I always split the data before resampling, and resample only the training rows. Otherwise copies of the same fraud leak into the test set and the score looks better than it is.
What is class imbalance, in plain words?
Class imbalance means one answer is far more common than the other. Google's machine learning course calls the common one the majority class and the rare one the minority class. Real data is usually like this. In card payments, fraud might make up less than 0.1 percent of the rows. Two words you will meet soon: recall is the share of real fraud you catch, and precision is the share of your fraud flags that are real.
Think of a hospital triage nurse who sees 500 patients a day, and only two have a rare, serious condition. A nurse who writes 'not serious' for everyone is right 498 times out of 500, and still useless. A model can fail in exactly the same way.
Here is the AI version. A card company's fraud model sees 10,000 payments, and 100 of them are fraud. A model that approves every payment is 99 percent accurate and catches no fraud at all.
Key words
- Majority class
- The common label, such as a legit payment.
- Minority class
- The rare label, such as fraud. It is usually the one you care about most.
- Class weight
- A number that makes a mistake on a rare example count for more during training.
- Decision threshold
- The score above which the model says yes. Set it on held-out data, meaning rows the model never trained on.
- Recall
- Of the real cases, the share you catch.
Why does a rare class hurt a model?
Two things go wrong. Plain accuracy looks fine, so nobody notices. And training sees too few rare examples to learn them. Google's guide gives a case with 200 common examples and 2 rare ones. With batches of 20, most batches hold no rare example at all.
- Trap
Accuracy looks great
A model that approves every payment scores 99 percent and finds no fraud.
- Better
Measure the rare class
Check recall and precision for fraud, not one overall score.
Google's guide says accuracy is usually a poor measure when a model is trained on imbalanced data. The rest of this answer shows what to do instead.
What are the main fixes?
There are three levers. Two change the training data or its weights, and one changes the cut-off after training.
Three levers for a rare class
Rare fraud, under 0.1%
plain accuracy hides the misses
Change the training data
Class weights
a miss counts for more in the loss
Resample the rows
more rare rows or fewer common ones
Trained model
scores each payment
Move the threshold
cut-off set on held-out data
Catches more fraud
judged on recall and precision
- 1Rare rows get more weight in the training loss.
- 2Or the rare rows are copied, and common rows are thinned out.
- 3Class weights are applied while the model trains.
- 4Resampled rows are what the model trains on.
- 5The model's scores go to a cut-off, picked on held-out data.
- 6More real fraud is caught, at a known cost in false alarms.
Class weights
Scikit-learn's balanced mode sets each class's weight from how common the class is. The rule is n_samples divided by (n_classes times the class count), so rare classes get large weights and common ones get small weights. Those weights also push the scores up for the rare class, so the decision threshold still needs tuning afterwards.
Resampling
Downsampling trains on fewer common rows. Upweighting then counts those kept rows more in the loss, so the model still learns the real mix. Oversampling copies or synthesises rare rows instead.
Decision threshold
After training, you choose the score above which the model says fraud. Pick it on held-out data, using what a miss and a false alarm each cost.
Here is the class-weight lever in plain Python. It is a different route from downsampling, which the next section covers, because it weights the rare class instead of resampling. The numbers are made up: 10,000 card payments, 100 of them fraud. No model is trained here, the code only shows the weights.
# A fraud model's training labels: 10,000 card payments, 100 of them fraud.
from collections import Counter
labels = [0] * 9900 + [1] * 100 # 0 = legit, 1 = fraud
counts = Counter(labels)
n_samples = len(labels)
n_classes = len(counts)
# The same formula scikit-learn uses for class_weight="balanced".
weights = {c: n_samples / (n_classes * counts[c]) for c in counts}
print("class counts:", dict(counts))
print("balanced weights:", {c: round(w, 3) for c, w in weights.items()})
# Each fraud example now counts about 99 times as much as a legit one in the loss.
print("fraud weight / legit weight:", round(weights[1] / weights[0], 1))
# A model that says "legit" for every payment still scores this well:
print("accuracy of always saying legit:", counts[0] / n_samples)Output
class counts: {0: 9900, 1: 100}
balanced weights: {0: 0.505, 1: 50.0}
fraud weight / legit weight: 99.0
accuracy of always saying legit: 0.99Run it and fraud gets a weight of 50, while legit gets about 0.5. Each fraud row counts 99 times as much as a legit row in the loss. The always-legit model still scores 99 percent accuracy, which is why accuracy is not enough.
Which lever first? Often the metric and the threshold come first, since they cost little to change. Add weights or resampling when the model still cannot learn the rare class.
How do downsampling and upweighting work?
For severe imbalance, Google's guide describes a two-step method. It sounds wrong at first, so the numbers help. Start with 99 legit payments for every fraud, as in the chart.
- 1
Step 1: keep fewer common rows
Keep one legit row in 25. The training mix moves from 99 percent legit to about 80 percent legit and 20 percent fraud.
- 2
Step 2: count each kept row 25 times
Multiply the loss on each kept legit row by 25. The model then learns the real fraud rate again.
Downsample, then upweight
Legit 99%, fraud 1%
the model sees a skewed mix
Step 1: downsample legit
keep 1 legit row in 25
Step 2: upweight legit x25
each kept legit row counts 25 times
Real fraud rate again
loss now counts the real mix
- 1Keep one legit row in 25 and drop the rest.
- 2Each kept legit row now counts 25 times in the loss.
- 3The real fraud rate is learned again.
Downsampling has costs as well as benefits. Google's guide notes faster convergence and less disk space, but it needs manual effort, especially on large datasets. Upweighting the rare class alone is simpler, but it can add more prediction bias.
Which numbers should you watch?
Recall is the share of real fraud you catch. Precision is the share of your fraud flags that are real. Balanced accuracy averages the recall of each class, so the rare class counts as much as the common one.
“Accuracy is usually a poor metric for assessing a model trained on a class-imbalanced dataset.”
Google's machine learning course
“It is defined as the average of recall obtained on each class.”
scikit-learn
The threshold trades these two numbers. Lower it and you catch more fraud, but flag more good payments. Scikit-learn's guide says the default cut-off is not ideal for most use cases, and suggests tuning the decision threshold once the model has been trained.
Medicine faces the same choice. The scikit-learn guide says a missed cancer costs much more than a further test, so it may be better to flag a patient when the estimate is much lower than 0.5.
Tip
In the interview, name the metric before the fix. Saying 'resample' first, before you know what you are measuring, is a common slip.
How would you handle a fraud model where fraud is 0.1 percent?
A bank's fraud team asks you to ship a model on a stream where 1 payment in 1,000 is fraud. Here is the order I would follow.
- 1
Split first
Split into training, validation and test sets before any resampling. Resample the training rows only, so no copy of a fraud case reaches the test set.
- 2
Start with a weighted baseline
Train with class weights, then log recall and precision on the validation set.
- 3
Tune the threshold on validation
Pick the cut-off that gives the recall the bank needs, while keeping the false alarms the review team can work through.
- 4
Test once, on untouched data
Report recall and precision on the test set, with the fraud count and the review hours each setting would cost.
- 5
Watch it after launch
Fraud patterns change. Track recall and the false-alarm rate each week, and re-tune the threshold when either drifts.
What does the interviewer want to hear?
A strong answer covers
- A plain definition: one label is much rarer, and accuracy hides the problem.
- Why it hurts: the model sees few rare examples, and the accuracy still looks fine.
- The fixes: class weights, resampling, and a moved decision threshold.
- The right numbers: recall, precision and balanced accuracy.
- Resample only the training data, after the split.
- Cost: which error hurts more, and what it means for the business.
Common traps
Trap"Accuracy is 99 percent, so the model works."
BetterCheck what the 99 percent is made of. An always-legit model scores the same and catches no fraud.
Trap"Resample the whole dataset, then split it."
BetterSplit first. Resampling before the split copies rare rows into the test set and inflates the score.
Trap"Always use a 0.5 threshold."
BetterThe cut-off is a business choice. Pick it on held-out data against the cost of a miss and of a false alarm.
Can you spot the mistake?
Spot the mistake
A teammate builds a fraud model. Which step is the mistake?
Quick check
A model flags 1 in 100 payments and catches 90 percent of real fraud, but most flags are false alarms. Which metric shows the false-alarm problem?
Can you answer these from memory?
Flash cards · tap a card to flip it
What will they ask next?
Learn it in depth
Last updated on 27 November 2026
Building a model that has to catch rare events?
I design and build AI products and agents, including the screens and the system behind the model. Book a short call and tell me what the rare case is and what a miss costs.