Custom loss with one hot encode

Hi all,
I am new to PyTorch. I need some help to implement a custom loss. So, my model output shape is [256,462](256 is minibatch size) and my target shape is [256], where the target is just label encoder. I want to write a function that receives target shape as [256] and convert to [256,462] one hot encode tensor. My number of class is 462. Then I want to do some calculations in GPU.
How can I convert the target shape of [256] to [256,462] with one hot encoding?

Thanks!

If the target contains the class indices, you could use F.one_hot:

target = torch.randint(0, 462, (256,))
target = F.one_hot(target)
1 Like