PythiloLesson 1 of 8 · progress kept in this browser

Practice in Lab: Differentiate masked focal loss under class imbalance →

Differentiate masked focal loss under class imbalance

Focal weighting changes which examples dominate the gradient. The factor depends on the current model probability and must participate in autograd; multiplying cross entropy by a detached difficulty score defines a different update. A declared reduction also matters when class weights and ignored examples interact. This Lab uses multiclass logits, one integer target per row and a fixed valid-row denominator. It exercises extreme scores and an entirely ignored batch without introducing undefined gradients.

Your task

Implement multiclass focal loss: mean of -alpha[y]*(1-p[y])**gamma*log(p[y]) over valid rows, normalized by the number of valid targets, not the sum of class weights. Use log-softmax, preserve autograd and return graph-connected zero when every target is ignored. Reject nonfinite logits, invalid shapes/dtypes/labels, negative or nonfinite gamma, and nonpositive/nonfinite class weights. Do not detach the focal factor.

This lesson uses torch, which Python in this browser does not include. Read it here, and run and check it in the Pythilo app on iPhone or iPad.