Compute balanced class weights for an imbalanced dataset

Fraud, toxicity and spam labels are rare. Weighting the loss by inverse class frequency stops the model from always guessing the majority class.

Write class_weights(y, n_classes). Return a float array of length n_classes with weight[c] = n_samples / (n_classes * count[c]). Classes that never appear get weight 0.

Signaturedef class_weights(y, n_classes)

Example

class_weights([0, 0, 0, 1], 2) is [0.667, 2.0].

Understand the idea

When one class is rare, say fraud, a model can score well by always guessing the common class. Class weights fix this by making each rare example count more in the loss. The balanced formula is chosen so the weights average to 1 over the samples, which keeps the overall loss size and learning rate unchanged. Worked example: y = [0, 0, 0, 0, 1, 1, 2], n_classes = 4, so 7 samples. Counts: [4, 2, 1, 0]. Weight for class 0 = 7 / (4 * 4) = 0.4375. Class 1 = 7 / (4 * 2) = 0.875. Class 2 = 7 / (4 * 1) = 1.75. Class 3 never appears, so its weight is 0. Check: 4 * 0.4375 + 2 * 0.875 + 1 * 1.75 = 5.25, and 5.25 / 7 = 0.75, because one of the four classes is empty; with all classes present the sample average is exactly 1. Rule: weight[c] = n_samples / (n_classes * count[c]) when count[c] > 0, else 0, as a float array. Plain inverse counts point the same way but are far too small. Used for fraud, toxicity and spam classifiers.

solution.pyPython idle
Ctrl/Cmd + Enter runs sample tests

Run checks the first 2 tests. Submit checks all 3.

  • Sample 1: exampleclass_weights([0, 0, 0, 1], 2)
  • Sample 2: missing classclass_weights([0, 2, 2, 2, 2], 3)
  • Test 3: balancedclass_weights([0, 1, 2, 0, 1, 2], 3)