I have a target with size of NxHxW, where N is batch size. I want to make one hot encoding with the output size of NxCxHxW for image segmentation.
def one_hot(targets):    
    targets_extend=targets.clone()
    targets_extend.unsqueeze_(1) # convert to Nx1xHxW
    one_hot = torch.cuda.FloatTensor(targets_extend.size(0), C, targets_extend.size(2), targets_extend.size(3)).zero_()
    one_hot.scatter_(1, targets_extend, 1) 
    return one_hot

In the above code, I have used targets_extend=targets.clone(), because the  targets will be used in the cross-entropy loss (only allows the size of NxHxW, instead of Nx1xHxW). More clears, the output of one hot encoding is used for BCE loss, while the targets used in the cross-entropy loss. Is my way (targets_extend=targets.clone()) correct in the making one hot encoding? Can I use targets_extend=targets.detach()? Thanks