Guides

Imbalanced classes: class weights, focal loss, oversampling and the decision threshold

With imbalanced classes, judge the model by balanced accuracy, the recall of the rare class and PR AUC instead of accuracy, move the decision threshold first, and use class weights, the focal loss or oversampling only when that is not enough. When 2 % of the rows are fraud, a model that never predicts fraud is 98 % accurate and useless; this guide shows how to see the problem in the metrics and when each of the four levers helps.

First, measure the right thing

Accuracy counts every row the same, so the large class dominates it. On imbalanced data, look at metrics that give the rare class its own weight:

  • Balanced accuracy, the mean recall over the classes: 50 % for a model that always predicts the larger of two classes, however unbalanced they are.
  • Recall and precision of the rare class: how many of its rows were found, and how many alarms were right.
  • PR AUC (average precision, for two classes), which says more than ROC AUC when positives are rare; a model that guesses gets the share of positives.
  • The confusion matrix, which shows exactly where the errors are.

Brick DNN reports all of them for every finished classification run, on the validation and the test rows. The readiness check of the Data tab points out classes that are more imbalanced than 3 : 1.

Four levers

What each lever changes, and where it is in Brick DNN
LeverWhat it changesWhere
Class weightsMistakes on the rare class cost more in training. balanced weighs each class by n / (k · count), so every class counts as much as a whole.Loss Weighted cross-entropy of a network; class_weight of gradient boosting and SVMs
Focal lossRows the network already classifies well count less (focal_gamma, default 2), so training concentrates on the hard ones; class weights can be added as its alpha.Loss Focal loss of a network
OversamplingRepeats rare rows of the training split (or drops common ones), which changes the class shares the model sees and makes epochs longer.Step Balance classes in the Data tab, training rows only
Decision thresholdChanges nothing in training: it moves the probability at which a row counts as positive.Under Metrics of a finished run with two classes

Start with the threshold

A model that ranks the rare rows above the common ones but rarely gives them a probability above 0.5 only needs a lower threshold. That costs nothing: no new training, no copied rows. Under Metrics of a finished binary run, a slider over the measured thresholds shows precision, recall, F1 and the counts of true and false positives on the validation and the test rows. Two buttons jump to the threshold with the best F1 and to the highest threshold with a recall of at least 80 %. Use this threshold for predictions saves it on the run, and from then on its predictions use it.

The positive class is the second one: in alphabetical order of text labels, index 1 for class indices. fraud before ok makes ok positive, so name the classes so that the rare one comes second, or use 0 and 1.

The evaluation of a finished run: a confusion matrix with the true classes in the rows and the predicted classes in the columns, almost all rows on the diagonal.
The confusion matrix of a finished run shows where the errors are.

Then weights or the focal loss

When the model does not separate the rare class well at any threshold (a low PR AUC), change what it learns. For gradient boosting and SVMs, set class_weight to balanced, as in the gradient boosting example. For a network, choose the weighted cross-entropy, or the focal loss when there are many easy and few hard rows. The run shows the weights it computed from the class counts of the training rows.

Weights and oversampling both push the predicted probabilities towards the rare class, so look at the threshold again afterwards. Combining weights and oversampling is rarely needed: they do much the same.

Oversampling, when the model needs to see more rare rows

Balance classes in the Data tab oversamples the rare class or undersamples the common one, by default in the training rows only: validation and test keep the real class shares, so their numbers stay honest. It suits models whose training does not take weights, and it is easy to reason about. The price is longer epochs and a model that sees the same rare rows many times, which can make it memorise them.

Compare the options fairly

Losses of different kinds cannot be compared with each other (a focal loss is smaller than the cross-entropy of the same model), so compare runs by their metrics. A hyperparameter search can try the losses for you: give it the list cross_entropy, weighted_cross_entropy and focal, and rank the trials by PR AUC, balanced accuracy or macro F1. A search over the loss ranked by the loss itself is refused for this reason.

The trials of a search for a gradient boosting model, each with its learning rate, depth, rows per leaf and class weights, and its cross-validated loss, accuracy and PR AUC; the best trial is highlighted.
A search that also tries class weights, ranked by PR AUC instead of accuracy.

In short

  1. Measure with balanced accuracy, recall of the rare class, PR AUC and the confusion matrix.
  2. Move the decision threshold; often that is enough.
  3. If the classes do not separate, use class weights or the focal loss, then set the threshold again.
  4. Oversample when the model cannot take weights, or to try it against them, on the training rows only.

Examples to start from

  • Gradient boosting classifier

    Gradient-boosted trees classify rows of 30 features; balanced class weights for rare classes.

    scikit-learn · HistGradientBoostingClassifier

  • SVM classifier

    A support vector machine with an RBF kernel classifies rows of 4 features, with probabilities.

    scikit-learn · SVC

  • Voting ensemble

    Gradient boosting, an SVM and a Gaussian process; soft voting averages their probabilities.

    scikit-learn · VotingClassifier

More guides

Open the editor