Class Weights, Focal Loss and Balanced Batches
Resampling changes the rows a model sees. There is a cheaper route to the same goal: keep the data as it is and change how much each row counts in the loss. Class weights make minority mistakes more expensive, focal loss makes hard examples more expensive, and balanced batches change which rows a mini-batch contains. None of them creates or deletes data, so there is nothing to leak and nothing to overfit to.
Class weights
The usual training loss is an average over the rows. A weighted loss multiplies each row's loss by the weight of its class:
Here is the number of classes and the number of rows of class . This choice, scikit-learn's class_weight="balanced", gives every class the same total weight . With 950 negatives and 50 positives, and . Mathematically, a weight of 10 on a row is the same as repeating it 10 times, so class weights are random oversampling without the copies and without the randomness.
import numpy as np
from sklearn.utils.class_weight import compute_class_weight
y = np.array([0] * 950 + [1] * 50)
w = compute_class_weight("balanced", classes=np.array([0, 1]), y=y)
by_hand = len(y) / (2 * np.bincount(y))
print("sklearn:", np.round(w, 3).tolist(), " by hand:", np.round(by_hand, 3).tolist())
print("total weight per class:", np.round(w * np.bincount(y), 1).tolist())sklearn: [0.526, 10.0] by hand: [0.526, 10.0]
total weight per class: [500.0, 500.0]
Most scikit-learn classifiers accept class_weight="balanced" or a dictionary such as {0: 1, 1: 5}; fit(X, y, sample_weight=...) gives per-row weights; XGBoost and LightGBM use scale_pos_weight. Compare them on the same imbalanced problem:
from sklearn.datasets import make_classification
from sklearn.linear_model import LogisticRegression
from sklearn.model_selection import train_test_split
from sklearn.metrics import recall_score, precision_score
X, y = make_classification(n_samples=3000, n_features=5, n_informative=3, n_redundant=0,
n_clusters_per_class=1, weights=[0.95], flip_y=0.01,
class_sep=1.0, random_state=1)
X_tr, X_te, y_tr, y_te = train_test_split(X, y, test_size=0.3, stratify=y, random_state=0)
print("test positives:", int(y_te.sum()), "of", len(y_te))
for cw in [None, {0: 1, 1: 5}, "balanced"]:
m = LogisticRegression(class_weight=cw, max_iter=1000).fit(X_tr, y_tr)
p = m.predict(X_te)
print(f"class_weight={str(cw):<14} recall={recall_score(y_te, p):.3f} "
f"precision={precision_score(y_te, p):.3f} flagged={int(p.sum())}")test positives: 49 of 900
class_weight=None recall=0.571 precision=0.903 flagged=31
class_weight={0: 1, 1: 5} recall=0.878 precision=0.439 flagged=98
class_weight=balanced recall=0.959 precision=0.260 flagged=181
A stratified 70/30 split, scored on the 900 test rows (49 positives). The unweighted model flags 31 rows and finds 28 of the 49 positives (recall 0.571) with high precision. A weight of 5 on the positives flags 98 rows (recall 0.878, precision 0.439), and the balanced weight of about 10 flags 181 (recall 0.959, precision 0.260). The weight is a dial between misses and false alarms: choose it on validation data, with the cost of each error in mind, exactly like the sampling ratio in the previous lesson.
Focal loss
Class weights treat every minority row alike. In detection problems with thousands of easy background boxes per object, the trouble is different: the many easy negatives, each with a tiny loss, still add up and dominate the gradient. Focal loss (Lin et al., 2017, for the RetinaNet detector) scales the cross-entropy down for examples the model already gets right. With the predicted probability of the true class,
The factor is near 0 for an easy example ( close to 1) and near 1 for a hard one. gives back cross-entropy; the paper's default is with for the positive class (and for the negative). The derivation of cross-entropy itself is in Loss Functions.
import numpy as np
def focal_loss(p, y, gamma=2.0, alpha=0.25):
"""Binary focal loss; p = predicted probability of class 1, y in {0, 1}."""
p_t = np.where(y == 1, p, 1 - p)
a_t = np.where(y == 1, alpha, 1 - alpha)
return -a_t * (1 - p_t) ** gamma * np.log(p_t)
y = np.array([0, 0, 1, 1])
p = np.array([0.05, 0.40, 0.90, 0.20]) # easy neg, unsure neg, easy pos, hard pos
ce = -np.log(np.where(y == 1, p, 1 - p))
fl = focal_loss(p, y)
for name, c, f in zip(["easy negative", "unsure negative", "easy positive", "hard positive"], ce, fl):
print(f"{name:<16} CE={c:.4f} FL={f:.4f} FL/CE={f / c:.4f}")
print("gamma=0, alpha=0.5 gives CE/2:", np.allclose(focal_loss(p, y, 0, 0.5), ce / 2))easy negative CE=0.0513 FL=0.0001 FL/CE=0.0019
unsure negative CE=0.5108 FL=0.0613 FL/CE=0.1200
easy positive CE=0.1054 FL=0.0003 FL/CE=0.0025
hard positive CE=1.6094 FL=0.2575 FL/CE=0.1600
gamma=0, alpha=0.5 gives CE/2: True
The easy examples keep only 0.19% (negative) and 0.25% (positive) of their cross-entropy, while the hard positive keeps 16% ( times ) and the unsure negative 12% ( times ). Relative to the easy examples, the hard ones now count about 50 to 85 times more than they did under plain cross-entropy.
The same function in PyTorch is torchvision.ops.sigmoid_focal_loss, which takes logits (scores before the sigmoid). This recorded example checks that it agrees with the NumPy version:
import numpy as np
import torch
from torchvision.ops import sigmoid_focal_loss
p = np.array([0.05, 0.40, 0.90, 0.20])
y = np.array([0.0, 0.0, 1.0, 1.0])
logits = torch.tensor(np.log(p / (1 - p)))
fl = sigmoid_focal_loss(logits, torch.tensor(y), alpha=0.25, gamma=2.0, reduction="none")
print([round(v, 4) for v in fl.tolist()])[0.0001, 0.0613, 0.0003, 0.2575]
Note: Focal loss is mostly used for neural networks (detection, segmentation, rare-event tagging), where you write the loss yourself. Gradient-boosting libraries accept it as a custom objective. For a logistic regression on a tabular problem, class weights or a threshold are simpler and usually enough.
Balanced batches
Neural networks train on mini-batches. With 2% positives and a batch of 32, most batches contain no positive at all, so many gradient steps never hear about the minority class. A balanced batch sampler draws each batch with a fixed share of each class, sampling minority rows with replacement. In PyTorch this is WeightedRandomSampler with per-row weights ; the idea fits in a few lines of NumPy:
import numpy as np
rng = np.random.default_rng(0)
y = np.array([1] * 20 + [0] * 980)
def balanced_batches(y, batch_size, n_batches, rng):
by_class = [np.flatnonzero(y == c) for c in np.unique(y)]
per_class = batch_size // len(by_class)
for _ in range(n_batches):
idx = np.concatenate([rng.choice(ix, per_class, replace=len(ix) < per_class) for ix in by_class])
yield rng.permutation(idx)
plain = [int(y[rng.choice(len(y), 32, replace=False)].sum()) for _ in range(5)]
print("positives per plain batch: ", plain)
balanced = [int(y[b].sum()) for b in balanced_batches(y, 32, 5, rng)]
print("positives per balanced batch:", balanced)positives per plain batch: [2, 0, 0, 0, 0]
positives per balanced batch: [16, 16, 16, 16, 16]
The model now sees the minority class in every step, but it also sees a 50/50 world. Its predicted probabilities are therefore too high for the minority class; recalibrate them, or move the threshold, before using them as real probabilities. The same warning holds for class weights and resampling.
Pitfalls
- Weighted training shifts probabilities: after class weights or balanced batches, no longer means a 50% chance. Calibrate on untouched validation data if probabilities matter.
- Double counting: class weights and oversampling and a lowered threshold all push in the same direction. Pick one main remedy and tune it.
- Weights in the metric: weight the loss for training, but report metrics on the real, unweighted validation and test data.
- Focal loss gamma too high: large also ignores medium-hard examples; tune (0.5–5) on validation data.
Practice
- Three classes have 600, 300 and 100 training rows. What are the
"balanced"weights?
Answer
with , : , and . Each class then has total weight .
- For a positive example with and , by what factor does focal loss (ignoring ) shrink the cross-entropy?
Answer
, so the loss is 16% of the cross-entropy. For the factor would be .
Test yourself
With 900 negatives and 100 positives, what is the balanced weight of a positive row?
- 0.1
- 1
- 5
- 9
What does the factor in focal loss do?
- Increases the loss of easy examples
- Shrinks the loss of examples the model already predicts confidently and correctly
- Normalises the probabilities
- Removes the minority class
Focal loss with is …
- zero
- cross-entropy weighted by
- the hinge loss
- mean squared error
Why should the predicted probabilities be recalibrated after training with balanced batches?
- They are always exactly right
- The model learned from a 50/50 world, so it overestimates the minority class
- Balanced batches make probabilities negative
- Calibration is needed only for regression