Index tensor must have the same number of dimensions as self tensor using unsqueez()

I am facing "Index tensor must have the same number of dimensions as self tensor " error while training my model. I am facing error on the line targets = zeros.scatter_(1, targets.unsqueeze(1).data.cpu(), 1). If anyone could help…
def init(self, num_classes, eps=0.1, use_gpu=True, label_smooth=True):

    super(CrossEntropyLoss, self).__init__()

    self.num_classes = num_classes

    self.eps = eps if label_smooth else 0

    self.use_gpu = use_gpu

    self.logsoftmax = nn.LogSoftmax(dim=1)

def forward(self, inputs, targets)

    log_probs = self.logsoftmax(inputs)

    zeros = torch.zeros(log_probs.size())

    targets = zeros.scatter_(1, targets.unsqueeze(1).data.cpu(), 1)

    if self.use_gpu:

        targets = targets.cuda()

    targets = (1 - self.eps) * targets + self.eps / self.num_classes

    return (-targets * log_probs).mean(0).sum()

Check the shape of zeros and make sure targets.unsqueeze(1) fits the expected shape requirement.
Based on the error, targets.unsqueeze(1) seems to have missing or additional dimensions.

i checked, torch.Size([32, 3, 224, 224]). still facing same error.

Assuming the posted shape is used in zeros and targets, it works for me:

zeros = torch.zeros(32, 3, 224, 224)
targets = torch.randint(0, 3, (32, 3, 224, 224))
zeros.scatter_(1, targets, 1)