Thanks a lot @BowieHsu!
I also found this one is very good.

  
      github.com
  
  
    DingKe/pytorch_workplace/blob/master/focalloss/loss.py 1.8k
import torch
import torch.nn as nn
import torch.nn.functional as F
from torch.autograd import Variable


def one_hot(index, classes):
    size = index.size() + (classes,)
    view = index.size() + (1,)

    mask = torch.Tensor(*size).fill_(0)
    index = index.view(*view)
    ones = 1.

    if isinstance(index, Variable):
        ones = Variable(torch.Tensor(index.size()).fill_(1))
        mask = Variable(mask, volatile=index.volatile)

    return mask.scatter_(1, index, ones)



  This file has been truncated. show original

  
  
    
    
  
  


I ported this code to my program and it works.