Class imbalance: weights and focal loss
Fraud is a few out of 1,000 payments. Broken parts are a few out of thousands. When the thing you want to find is rare, a model can learn only the common class and still get a high score. Move the γ slider to see how much the loss of easy examples shrinks, then step through how the focal loss formula is built.
Short answer. When one class is much more common, common, easy examples fill up the total loss and the model learns less about the rare class. There are four fixes: give the rare class's loss more weight, oversample the rare class or undersample the common one, use focal loss −α·(1 − p)^γ·log p to shrink the loss of easy examples, or keep the model and move the decision threshold. Measure with precision, recall and the PR curve, not accuracy.
p is the probability the model gave the right class. Near 1 means an easy example it already gets right. Near 0 means a hard example it gets wrong. Change γ with the slider or the number box (0 to 5) and only the blue focal loss curve moves. The green cross-entropy does not depend on γ. Losses above 3 are cut off at the top. This is a small stand-in that draws the formulas only, with no real model.
Try this. ① At the start, γ = 2. The easy example's loss goes from 0.105 to 0.00105, one hundredth. The hard example goes from 2.3 to 1.87, 0.81 times. Hard ÷ easy goes from 21.9 times to 1,770 times. ② Set γ to 0 and the two curves lie on top of each other: focal loss becomes cross-entropy. ③ At γ = 1 the ratio is 197 times, and with 990 easy and 10 hard examples, the hard ones are 66.5% of the total (18.1% at γ = 0, 94.7% at γ = 2). ④ Push γ to 5 and the share reaches 100.0%, but the hard example's loss also drops from 2.3 to 1.36. A large γ makes the whole learning signal smaller.
Definitions
The text below explains with pictures and experiments. The textbook definitions are as follows. The rare side is positive (answer y = 1), the common side is negative (y = 0), p is the probability of positive that the model gives, and log is the natural log.
- class imbalance
- A state of the data where one class has far more examples than another. The larger side is the majority class and the smaller side is the minority class.
- class weight
- A method that multiplies each example's loss by a weight wc set for that example's answer class, so the minority class's loss counts more. Used with cross-entropy, it is weighted cross-entropy. The common balanced choice uses the total number of examples N, the number of classes C, and the number of examples in class c, Nc, to give the weight below.
- oversampling, undersampling
- Oversampling grows the minority class in the training data by putting its examples in again or making new ones. Undersampling shrinks the majority class by using only part of its examples. Both only change the class ratio of the training data, and are done only on the training data after splitting into training and test.
- focal loss
- Cross-entropy multiplied by (1 − pt)^γ and by a class weight αt. pt is the probability given to the answer class (p if positive, 1 − p if negative), αt is α if positive and 1 − α if negative, and γ ≥ 0. It cuts the loss of examples already answered well (pt near 1), and with γ = 0 and αt = 1 it is the same as cross-entropy −log pt.
- threshold moving
- Keeping the trained model as it is and changing the threshold (usually 0.5) above which p is judged positive. The threshold is chosen on validation data.
- precision, recall, F1 score
- TP is the number of positives judged positive, FP the number of negatives wrongly judged positive, and FN the number of positives missed as negative. Precision P is the share of real positives among those judged positive, recall R is the share judged positive among the real positives, and F1 is their harmonic mean.
1. What happens when one class is much more common
Class imbalance means one kind of answer (class) shows up far more often than another. For example, 990 normal payments and 10 fraud cases. Two things go wrong.
- The score lies. A model that always says "normal" gets 990 of 1,000 right: 99% accuracy. It finds no fraud at all.
- Training leans toward the common class. The model learns by making the sum of the losses over all the data smaller (gradient descent). If common examples are 99 times more numerous, they win the sum even when each one has a small loss. Getting the rare ones wrong only adds a little.
The loss is cross-entropy, −log p, where p is the probability the model gave the right class. Here are the two examples from the lab above.
| Example | Probability p given to the right class | Cross-entropy −log p |
|---|---|---|
| Easy (already right) | 0.9 | 0.105 |
| Hard (wrong) | 0.1 | 2.3 |
One hard example costs 21.9 times as much as one easy example. But if there are 99 times more easy ones, the easy side has the bigger sum. Section 3 counts it out.
2. How the formula is built
Focal loss is cross-entropy multiplied by two extra pieces. Press "Next" and the formula gains one piece at a time (the orange background marks the new piece), and the curves in the picture change to match. The easy (p = 0.9) and hard (p = 0.1) examples are the same as in the lab above, and γ is fixed at 2.
- Start:
−log p. This is cross-entropy. It goes to 0 as the model gets it right (p → 1) and grows without limit as it gets it wrong (p → 0). Even an easy example has a loss above 0 (0.105), so many of them can fill up the sum. - Shrink the easy ones:
(1 − p)^γ · (−log p).1 − psays "how wrong is it". For a well-classified example it is close to 0, so raising it to the power γ and multiplying almost wipes out the loss. For a wrong example it is close to 1, so the loss stays almost the same. Why: the more the easy ones shrink, the more the hard ones make up the sum, so training focuses on the hard ones. In the paper's words, with p = 0.9 and γ = 2 the loss is 100 times smaller, and for p of 0.5 or less it is at most 4 times smaller. - Class weight:
α · (1 − p)^γ · (−log p). Multiply the rare class's loss by α and the common class's loss by 1 − α. The picture uses α = 0.75. Why: (1 − p)^γ only looks at whether an example is easy or hard, not at its class. α handles the balance between classes. Using α alone (γ = 0) is weighted cross-entropy, in other words class weights. - Done:
FL(p_t) = −α_t · (1 − p_t)^γ · log p_t. p is the probability of "positive", so when the right answer is negative, the probability given to the right class is 1 − p. Wrap that up as p_t (p for a positive, 1 − p for a negative) and both classes fit one formula. α_t is α for a positive and 1 − α for a negative. With γ = 0 and α_t = 1 it is cross-entropy again.
Try this. Watch "the share of the hard examples" in the text under the picture at each step. With 990 easy and 10 hard examples it climbs ① 18.1% → ② 94.7% → ③ 98.2%. At ③, the rare class's hard example is 1.4 and the common class's easy example is 0.000263.
The value of α can surprise you. In the paper's experiments, with γ = 0 (cross-entropy with α only), α = 0.75 for the rare class (objects) worked best. With γ = 2, α = 0.25 worked best. The paper says α should go down a little as γ goes up. γ and α affect each other, so pick them together. torchvision's sigmoid_focal_loss also defaults to α = 0.25 (for the positive class) and γ = 2.
3. Work it out by hand: 990 and 10
Say the 990 examples of the common class are all easy (the model already gives them p = 0.9) and the 10 examples of the rare class are all hard (p = 0.1).
- Accuracy. Always answering "common" gives
990 ÷ 1000 = 99%. Rare examples found: 0. - Sum of cross-entropy. Common side
990 × 0.105 = 104, rare side10 × 2.3 = 23. The rare side's share is23 ÷ (104 + 23) = 18.1%. - Class weights (scikit-learn's balanced). Weight = total count ÷ (number of classes × count of that class). Common:
1000 ÷ (2 × 990) = 0.505. Rare:1000 ÷ (2 × 10) = 50. Now each class's weights add up to the same amount:990 × 0.505 = 500and10 × 50 = 500. The loss sums are 52.7 for the common side and about 1,151 for the rare side, a 95.6% share. - Focal loss (γ = 2). Common
990 × 0.00105 = 1.04, rare10 × 1.87 = 18.7. Share 94.7%. Add α = 0.75 and it is 0.261 and 14, so 98.2%.
| Method | Sum over the 990 common | Sum over the 10 rare | Rare share |
|---|---|---|---|
| Cross-entropy | 104 | 23 | 18.1% |
| Class weights (balanced) | 52.7 | 1,151 | 95.6% |
| Cross-entropy + α = 0.75 only | 26.1 | 17.3 | 39.8% |
| Focal loss (γ = 2) | 1.04 | 18.7 | 94.7% |
| Focal loss (γ = 2, α = 0.75) | 0.261 | 14 | 98.2% |
Weights look at the class and shrink the whole common side. Focal loss looks at how easy an example is and shrinks the ones already right. Here every common example is easy, so the results look alike. If the common class has hard examples too, focal loss does not shrink those.
4. Properties to know
| Property | In plain words | Where to see it |
|---|---|---|
| γ = 0 gives cross-entropy | Focal loss is a wider version of cross-entropy. γ sets how much it shrinks | Lab ① at γ = 0 |
| The easier, the more it shrinks | With γ = 2: one hundredth at p = 0.9, at most one quarter for p ≤ 0.5 | Lab ① at γ = 2 |
| A large γ shrinks hard examples too | At p = 0.1 with γ = 5: 2.3 → 1.36. Too large and the learning signal gets weak | Lab ① at γ = 5 |
| α only changes the height | It keeps the shape of the curve and only sets the balance between classes | Section 2, step ③ |
| Weights and resampling inflate probabilities | A model trained with weights, oversampling or undersampling gives the rare class a higher probability than the real rate. Be careful if you use the probabilities as they are | Section 5 |
5. Four fixes
- Class weights. Multiply the rare class's loss by a bigger number. The data stays the same. The balanced weights in section 3 are a common starting point.
- Oversampling and undersampling. Put rare examples in several times (oversampling) or use only part of the common examples (undersampling) so the training data is more even. Oversampling can copy examples, or use SMOTE, which makes new examples between a rare example and its close neighbors. Do it only on the training data, and after splitting into training and test sets. If you do it first, copies of the same example end up in the test set too (see data leakage on the data splits page).
- Focal loss. Section 2. It shrinks the loss of easy examples so training focuses on the hard ones.
- Moving the threshold. Keep the trained model and change the 0.5 in "rare if its probability is over 0.5". Lower it to find more rare examples, at the cost of more false alarms. Pick the threshold from the PR curve on a validation set (logistic regression, ROC curve).
# scikit-learn: class weights
LogisticRegression(class_weight="balanced")
# PyTorch: one weight per class (common, rare)
loss_fn = torch.nn.CrossEntropyLoss(weight=torch.tensor([0.505, 50.0]))
# two classes (positive and negative): a number to multiply the positive loss by, e.g. 990 / 10
loss_fn = torch.nn.BCEWithLogitsLoss(pos_weight=torch.tensor([99.0]))
# torchvision: focal loss (defaults alpha=0.25, gamma=2)
loss = torchvision.ops.sigmoid_focal_loss(logits, targets, alpha=0.25, gamma=2, reduction="mean")
6. When to use what
| Option | Good | Bad | Use it when |
|---|---|---|---|
| Move the threshold | No retraining. Probabilities stay the same, only the decision changes | Cannot help if the model barely learned the rare class. Needs a validation set to pick it | Try it first. When a false alarm and a miss cost different amounts (screening, fraud) |
| Class weights | One line to turn on. No data added or thrown away | Rare class probabilities get inflated. Very large weights let a few rare examples shake training | Moderate imbalance and you can choose the loss. A default thing to try for most models |
| Oversampling | No change to the model or loss. Works with tools whose loss you cannot change | Repeating the same examples makes it easy to overfit them. Training takes longer. Probabilities get inflated | Small data with very few rare examples |
| Undersampling | Less data, so training is faster | Throws away information about the common class. Probabilities get inflated | So many common examples that using them all is too heavy |
| Focal loss | Works better the more easy examples there are. Looks at easy versus hard, not just the class | γ and α must be tuned together. Does not shrink hard examples of the common class | Easy examples fill up the loss. Object detection, where most candidates are background |
7. What to measure instead of accuracy
Call the rare class "positive" and compare what the model called positive with the truth.
| Measure | Meaning | Formula |
|---|---|---|
| Recall | Of the real positives, how many were found. Few misses? | positives found ÷ real positives |
| Precision | Of the ones called positive, how many were right. Few false alarms? | positives found ÷ number called positive |
| F1 | Precision and recall in one number (harmonic mean) | 2 × precision × recall ÷ (precision + recall) |
| PR curve, average precision | Precision and recall across every threshold, not tied to one threshold | Average precision measures the area under the curve |
Example. The model finds 8 of the 10 rare examples and wrongly calls 50 of the 990 common ones positive. Recall is 8 ÷ 10 = 80.0% and the false positive rate is 50 ÷ 990 = 5.1%, but precision is 8 ÷ 58 = 13.8%. The false positive rate, the across axis of the ROC curve, divides by the whole common class, so 50 false alarms look small. Precision shows plainly that 50 of the 58 alarms are false. That is why, with heavy imbalance, the PR curve tells you more than the ROC curve (Saito and Rehmsmeier). Keep the test set at its real class mix: do not oversample or undersample it.
Where it is used
- Fraud and anomaly detection. Find the rare odd record among mostly normal ones.
- Medical screening and defect detection. A miss is costly, so watch recall and lower the threshold.
- Object detection. Most candidate spots in a picture are background. This is where focal loss came from.
- Classifying rare words or rare categories. With many categories and a few rare ones, class weights are common.
Frequently asked questions
Accuracy is 99%. Why is the model bad?
If the rare class is only 1% of the data, a model that always answers with the common class is 99% accurate. It never finds a single rare example (recall 0). Accuracy is decided almost entirely by the common class, so measure the rare class on its own with precision, recall and the PR curve.
How are class weights different from oversampling?
Putting a rare example in k times and multiplying its loss by k give the same total loss. The difference: oversampling makes the data bigger, so each pass takes longer and the model sees the same examples again and again. Weights keep the data as it is and only change the loss. Both push the model's probabilities up for the rare class.
When should I use focal loss?
Use it when there are so many easy, already-correct examples that they fill up the total loss. The original paper made it for object detection, where most candidate spots are background. γ and α have to be tuned together. In the paper's experiments, α = 0.25 worked best with γ = 2.
Words
| Words used here | Textbook terms |
|---|---|
| one class is much more common | class imbalance, imbalanced data |
| common class, rare class | majority class, minority class |
| a number multiplied into each class's loss | class weight, weighted cross-entropy |
| putting in more, using fewer | oversampling, undersampling, SMOTE |
| a loss that shrinks easy examples | focal loss. (1 − p_t)^γ is the modulating factor, γ the focusing parameter |
| probability given to the right class | p_t |
| moving the decision threshold | threshold moving, threshold tuning |
| few misses, few false alarms | recall, precision, F1 score |
| the precision and recall curve and its area | precision-recall (PR) curve, average precision |
| share of negatives called positive | false positive rate |
Sources
- Tsung-Yi Lin, Priya Goyal, Ross Girshick, Kaiming He, Piotr Dollár, Focal Loss for Dense Object Detection, arXiv:1708.02002. α-balanced cross-entropy (α set by inverse class frequency or by cross validation), the focal loss formula, γ = 0 equals cross-entropy, 100 times at p_t = 0.9, γ = 2 with α = 0.25, Table 1.
- torchvision docs: sigmoid_focal_loss (defaults alpha=0.25, gamma=2; alpha weights the positive class).
- scikit-learn docs: compute_class_weight (balanced = n_samples / (n_classes × count per class)).
- Takaya Saito, Marc Rehmsmeier, The Precision-Recall Plot Is More Informative than the ROC Plot When Evaluating Binary Classifiers on Imbalanced Datasets, PLOS ONE.