Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Pytorch: Weight in cross entropy loss

I was trying to understand how weight is in CrossEntropyLoss works by a practical example. So I first run as standard PyTorch code and then manually both. But the losses are not the same.

from torch import nn
import torch
softmax=nn.Softmax()
sc=torch.tensor([0.4,0.36])
loss = nn.CrossEntropyLoss(weight=sc)
input = torch.tensor([[3.0,4.0],[6.0,9.0]])
target = torch.tensor([1,0])
output = loss(input, target)
print(output)
>>1.7529

Now for manual Calculation, first softmax the input:

print(softmax(input))
>>
tensor([[0.2689, 0.7311],
        [0.0474, 0.9526]])

and then negetive log of the correct class probality and multiply with the respective weight:

((-math.log(0.7311)*0.36) - (math.log(0.0474)*0.4))/2
>>
0.6662

What I am missing here?

like image 264
user3363813 Avatar asked Dec 06 '25 09:12

user3363813


2 Answers

To compute class weight of your classes use sklearn.utils.class_weight.compute_class_weight(class_weight, *, classes, y) read it here
This will return you an array i.e weight.
eg .

x = torch.randn(20, 5) 
y = torch.randint(0, 5, (20,)) # classes
class_weights=class_weight.compute_class_weight('balanced',np.unique(y),y.numpy())
class_weights=torch.tensor(class_weights,dtype=torch.float)
 
print(class_weights) #([1.0000, 1.0000, 4.0000, 1.0000, 0.5714])

Then pass it to nn.CrossEntropyLoss's weight variable

criterion = nn.CrossEntropyLoss(weight=class_weights,reduction='mean')

loss = criterion(...)
like image 190
Prajot Kuvalekar Avatar answered Dec 08 '25 21:12

Prajot Kuvalekar


For any weighted loss (reduction='mean'), the loss will be normalized by the sum of the weights. So in this case:

((-math.log(0.7311)*0.36) - (math.log(0.0474)*0.4))/(.4+.36)
>> 1.7531671457872036
like image 36
user3363813 Avatar answered Dec 08 '25 22:12

user3363813