RuntimeError: 1only batches of spatial targets supported (3D tensors) but got targets of size: : [1, 3, 96, 128]

I am using UNet

I have images with masks (black background and highlighted portion contain different RGB colors) and 12 classes. I want to do training using uNET. but i got error. “RuntimeError: 1only batches of spatial targets supported (3D tensors) but got targets of size: : [1, 3, 360, 640]”

Please help me

Kind Regards,
Khawar

Error

  File "/home/khawar/Pytorch-UNet/train.py", line 185, in <module>
    val_percent=args.val / 100)
  File "/home/khawar/Pytorch-UNet/train.py", line 84, in train_net
    loss = criterion(masks_pred, true_masks)
  File "/home/khawar/.local/lib/python3.6/site-packages/torch/nn/modules/module.py", line 722, in _call_impl
    result = self.forward(*input, **kwargs)
  File "/home/khawar/.local/lib/python3.6/site-packages/torch/nn/modules/loss.py", line 948, in forward
    ignore_index=self.ignore_index, reduction=self.reduction)
  File "/home/khawar/.local/lib/python3.6/site-packages/torch/nn/functional.py", line 2422, in cross_entropy
    return nll_loss(log_softmax(input, 1), target, weight, None, ignore_index, None, reduction)
  File "/home/khawar/.local/lib/python3.6/site-packages/torch/nn/functional.py", line 2220, in nll_loss
    ret = torch._C._nn.nll_loss2d(input, target, weight, _Reduction.get_enum(reduction), ignore_index)
RuntimeError: 1only batches of spatial targets supported (3D tensors) but got targets of size: : [1, 3, 96, 128]
1 Like

The target tensor for a multi-class segmentation use case using nn.CrossEntropyLoss or nn.NLLLoss should have the shape [batch_size, height, width] and contain the class indices in the range [0, nb_classes-1].
If your current target is an RGB image containing color codes for each class, you would have to map these colors to class indices first, e.g. by using a lookup table.

Hi! Even I am facing the same error, what exactly do you mean by a look up table. You mean convert RGB to monochrome?

No, I meant you would have to convert the colors to class indices.
If your dataset doesn’t provide the mapping, you could create your own as described here.

1 Like

Thanks a lot! It worked :slight_smile: