Target size (torch.Size([12])) must be the same as input size (torch.Size([12, 1000]))
I am using models.vgg16(pretrained=True) model for image classification, where number of classes = 3.

Batch size is 12 trainloader = torch.utils.data.DataLoader(train_data, batch_size=12, shuffle=True) since error says Target size (torch.Size([12])) must be the same as input size (torch.Size([12, 1000]))

I have changed last fc layer parameters and got last FC layer as  Linear(in_features=1000, out_features=3, bias=True)

Loss function is BCEWithLogitsLoss()

criterion = nn.BCEWithLogitsLoss()
optimizer = optim.SGD(vgg16.parameters(), lr=0.001, momentum=0.9)


Training code is  

        # zero the parameter gradients
        optimizer.zero_grad()
        outputs = vgg16(inputs)               #----&gt; forward pass
        loss = criterion(outputs, labels)   #----&gt; compute loss #error occurs here
        loss.backward()                     #----&gt; backward pass
        optimizer.step()                    #----&gt; weights update


While computing loss, I get this error Target size (torch.Size([12])) must be the same as input size (torch.Size([12, 1000]))

code is available at: code

Try to double check how you modified the linear layer. It seems that somehow the model does not forward pass through it.

Your model output have 1000 output size for each sample, while it should have 3. That's the reason you cannot evaluate the loss, since you try to compare 1000 classes to 3. You should have 3 outputs in your last layer, and that should work.

EDIT

From the code you shared here: link, I think there are two problems.

First, you modifed your model this way:

# Load the pretrained model from pytorch
vgg16 = models.vgg16(pretrained=True)

vgg16.classifier[6].in_features = 1000
vgg16.classifier[6].out_features = 3


while what you did here is to add a layer as an attribute to your network, you should also modify the forward() function of your model. Adding the layer as an attribute in the list doesn't apply the layer when forwardpassing the input.

Usually the way to do this properly is to define new class which inherits from the model you want to implement - class myvgg16(models.vgg16) or more generally class myvgg(nn.Module). You can find further explanation in the following link

If it fails, try to unsqueeze(1) your targets size (i.e. the lables variable). This is less likly to be the reason for the error but worth a try.

EDIT

Give another try of converting your target tensor to one hot vectors. And change the tensor type to Float as the BCELoss receives floats. 
