TExcelTAD
Home › Data Preparation Toolkit: Cleaning to Leakage-Free Splits › Class Weights, Focal Loss and Balanced Batches

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 nn rows. A weighted loss multiplies each row's loss by the weight of its class:

L=1n∑i=1nwyi ℓ(yi,p^i),wc=nK ncL = \frac{1}{n} \sum_{i=1}^{n} w_{y_i} \, \ell(y_i, \hat{p}_i), \qquad w_c = \frac{n}{K \, n_c}

Here KK is the number of classes and ncn_c the number of rows of class cc. This choice, scikit-learn's class_weight="balanced", gives every class the same total weight n/Kn/K. With 950 negatives and 50 positives, w0=1000/1900≈0.53w_0 = 1000/1900 \approx 0.53 and w1=1000/100=10w_1 = 1000/100 = 10. 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.

python · try it yourself
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:

python · try it yourself
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 ptp_t the predicted probability of the true class,

CE=−log⁡pt,FL=−αt (1−pt)γlog⁡pt\text{CE} = -\log p_t, \qquad \text{FL} = -\alpha_t \, (1 - p_t)^{\gamma} \log p_t

The factor (1−pt)γ(1 - p_t)^{\gamma} is near 0 for an easy example (ptp_t close to 1) and near 1 for a hard one. γ=0\gamma = 0 gives back cross-entropy; the paper's default is γ=2\gamma = 2 with α=0.25\alpha = 0.25 for the positive class (and 1−α1 - \alpha for the negative). The derivation of cross-entropy itself is in Loss Functions.

python · try it yourself
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% (0.82=0.640.8^2 = 0.64 times α=0.25\alpha = 0.25) and the unsure negative 12% (0.42=0.160.4^2 = 0.16 times 1−α=0.751 - \alpha = 0.75). 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:

python · try it yourself
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 1/nyi1/n_{y_i}; the idea fits in a few lines of NumPy:

python · try it yourself
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, p^=0.5\hat{p} = 0.5 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 γ\gamma also ignores medium-hard examples; tune γ\gamma (0.5–5) on validation data.

Practice

  1. Three classes have 600, 300 and 100 training rows. What are the "balanced" weights?
Answer

wc=n/(Knc)w_c = n/(K n_c) with n=1000n = 1000, K=3K = 3: 1000/1800≈0.5561000/1800 \approx 0.556, 1000/900≈1.1111000/900 \approx 1.111 and 1000/300≈3.3331000/300 \approx 3.333. Each class then has total weight 1000/31000/3.

  1. For a positive example with p=0.6p = 0.6 and γ=2\gamma = 2, by what factor does focal loss (ignoring α\alpha) shrink the cross-entropy?
Answer

(1−pt)γ=0.42=0.16(1 - p_t)^{\gamma} = 0.4^2 = 0.16, so the loss is 16% of the cross-entropy. For p=0.95p = 0.95 the factor would be 0.052=0.00250.05^2 = 0.0025.

Test yourself

With 900 negatives and 100 positives, what is the balanced weight of a positive row?

  1. 0.1
  2. 1
  3. 5
  4. 9

What does the factor (1−pt)γ(1 - p_t)^{\gamma} in focal loss do?

  1. Increases the loss of easy examples
  2. Shrinks the loss of examples the model already predicts confidently and correctly
  3. Normalises the probabilities
  4. Removes the minority class

Focal loss with γ=0\gamma = 0 is …

  1. zero
  2. cross-entropy weighted by αt\alpha_t
  3. the hinge loss
  4. mean squared error

Why should the predicted probabilities be recalibrated after training with balanced batches?

  1. They are always exactly right
  2. The model learned from a 50/50 world, so it overestimates the minority class
  3. Balanced batches make probabilities negative
  4. Calibration is needed only for regression