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.
Prepare offline
Choose Download entire course or Download entire category first. After completion, code and checks run locally on CPU. The independent example needs no account, remote service or API key.
import torch
x = torch.tensor([[2., 0.]])
print(x.log_softmax(-1).exp())Review the evidence
Compare gamma zero with cross entropy, then inspect derivatives at a difficult example. Explain why class weighting, focal weighting and resampling are different interventions. Measure rare-group errors on held-out data before choosing them.
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.
The explanation opens here once every check passes.