# 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.

AI and LLM interview question Q425, Classic ML and deep-learning basics. Intermediate, common (our estimate). From Venkat R. Murty's free Interview Kit: https://designervenkat.online/interview/ai/how-do-you-handle-class-imbalance

## Say it in 30 seconds

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.

## Say it in 2 minutes

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.

- **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.

*Diagram, Three levers for a rare class: A rare outcome needs a lever in training, in the cut-off, or both. The model scores each payment, and the threshold turns that score into a flag. Judge the result by how much fraud it catches and how many false alarms it raises.*
1. Rare rows get more weight in the training loss.
2. Or the rare rows are copied, and common rows are thinned out.
3. Class weights are applied while the model trains.
4. Resampled rows are what the model trains on.
5. The model's scores go to a cut-off, picked on held-out data.
6. More 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.

```python
# 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:

```text
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.99
```

Run 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.

*Diagram, Downsample, then upweight: Start with 99 legit payments for every fraud. Keep one legit row in 25 so training sees about 20 percent fraud, then count each kept legit row 25 times. The weights bring back the real fraud rate, so the predictions are not pushed towards fraud.*
1. Keep one legit row in 25 and drop the rest.
2. Each kept legit row now counts 25 times in the loss.
3. The 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." Better: Check 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." Better: Split first. Resampling before the split copies rare rows into the test set and inflates the score.
- Trap: "Always use a 0.5 threshold." Better: The 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?

A. He oversamples the fraud rows across the whole dataset, then splits it into train and test.
B. He reports recall and precision on the test set.
C. He tunes the decision threshold on the validation set.
D. He sets class weights in the training step.

**Answer:** A. Oversampling the whole set before the split copies fraud rows into the test set, so the score looks better than it will be in production. Resample only the training rows, after the split.

**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?

A. Accuracy
B. Precision
C. Recall
D. Balanced accuracy

**Answer:** B. Precision is the share of flags that are real fraud, so it falls when most flags are false alarms. Recall only counts the real frauds you caught, and accuracy and balanced accuracy do not show how many flags are false alarms.

## Can you answer these from memory?

**Flash cards**

- **What is class imbalance?** One label is far more common than the other, so the rare one gets too little attention.
- **Why is accuracy misleading?** A model that always predicts the common label can score high while missing every rare case.
- **What is a class weight?** A number that makes a mistake on a rare example count more in the training loss.
- **Downsample then upweight?** Keep fewer common rows, then multiply their loss by the same factor so the mix stays honest.
- **Which metric for the rare class?** Recall (share caught), precision (share of flags that are real), or balanced accuracy.
- **When do you resample?** After the split, on the training rows only. Resampling first leaks copies into the test set.

## Likely follow-up questions

- Q420 Precision, recall and F1? https://designervenkat.online/interview/ai/precision-recall-and-f1
- Q421 ROC-AUC vs PR-AUC? https://designervenkat.online/interview/ai/roc-auc-vs-pr-auc
- Q422 Train/validation/test splits? https://designervenkat.online/interview/ai/train-validation-test-splits
- Q424 What is data leakage? https://designervenkat.online/interview/ai/what-is-data-leakage
- Q419 MSE vs cross-entropy loss? https://designervenkat.online/interview/ai/mse-vs-cross-entropy-loss

## Learn it in depth

- [Precision: is a yes really a yes?](https://designervenkat.online/learn/machine-learning/precision)
- [Recall: how many real yeses you catch](https://designervenkat.online/learn/machine-learning/recall)
