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?
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(...)
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With