Using focal loss from kornia in fastai v1

I am trying something like,

from kornia.losses import focal
learn = cnn_learner(data, arch)
learn.loss_func=focal.FocalLoss(alpha= 0.5, gamma=2.0)
learn.lr_find()

I get ValueError: Expected target size (8,), got torch.Size([8, 28]). The batch size is 8 and number of classes are 28.

~/anaconda3/lib/python3.7/site-packages/kornia/losses/focal.py in focal_loss(input, target, alpha, gamma, reduction, eps)

   38     if target.size()[1:] != input.size()[2:]:
   39         raise ValueError('Expected target size {}, got {}'.format(
---> 40             out_size, target.size()))
   41 
   42     if not input.device == target.device:

How can I ensure the sizes match?

Are you are doing a multi classification problem? That loss expects single classification so there should be no dimention used for the class as its always 1.

3 Likes

Ah I see. Yes, I was using it for multi-class classification. Thanks!