RuntimeError: only batches of spatial targets supported (3D tensors) but got targets of dimension: 1

Hello I am having this error when I try to quantize this model of Unsupervised segmentation demo_ref.py. For this I have been using the resnet18_quant.py quantization example. I will copy again how the network is defined:

class MyNet(nn.Module):
    def __init__(self,input_dim):
        super(MyNet, self).__init__()
        self.conv1 = nn.Conv2d(input_dim, args.nChannel, kernel_size=3, stride=1, padding=1 )
        self.bn1 = nn.BatchNorm2d(args.nChannel)
        self.conv2 = nn.ModuleList()
        self.bn2 = nn.ModuleList()
        for i in range(args.nConv-1):
            self.conv2.append( nn.Conv2d(args.nChannel, args.nChannel, kernel_size=3, stride=1, padding=1 ) )
            self.bn2.append( nn.BatchNorm2d(args.nChannel) )
        self.conv3 = nn.Conv2d(args.nChannel, args.nChannel, kernel_size=1, stride=1, padding=0 )
        self.bn3 = nn.BatchNorm2d(args.nChannel)

    def forward(self, x):
        x = self.conv1(x)
        x = F.relu( x )
        x = self.bn1(x)
        for i in range(args.nConv-1):
            x = self.conv2[i](x)
            x = F.relu( x )
            x = self.bn2[i](x)
        x = self.conv3(x)
        x = self.bn3(x)
        return x

Can someone help me?

Hey print your target, input shape and see.

If you use a cross entropy loss function then,
The shapes of input and target should be like:

Example:
Input: (1,1,160,160)
Target:(1,160,160)
Hope this helps

Hello, yes I am using cross entropy loss function. when I call loss = loss_fn(outputs, labels) I get this error. If I print the size of outputs and labels I have this:
size outputs: torch.Size([3, 100, 224, 224])
size labels: torch.Size([3])
So what should I do to have labels as [100,224,244]?

Hey,
A torch.Size([3]) is just the batch size that you are passing through. So, to elaborate a bit more torch.Size([3, 100, 224, 224]) - 4 dimension
3 - is batch size
100 - is the number of channels
224, 224, - image (w, h)

Exactly, your target should be torch.Size([3, 224, 224]).
Take a look at the documentation of the CE loss for further refrence.

A small example

outputs = torch.rand(3, 100, 224, 224).float() # ex: outputs = model(input)
targets = torch.rand(3, 224, 224).long() # try to change it to torch.rand(3) and see

criterion = torch.nn.CrossEntropyLoss()
loss = criterion(input, targets)
print(loss)