Pytorch ValueError: Target and input must have the same number of elements after change Image size
i have a working peace of code, which takes a Batchsize from 32 Image with the shape of 256*256 and i can train my neuronal network. 

class Netz(nn.Module):
def __init__(self):
    super(Netz,self).__init__()
    self.conv1 = nn.Conv2d(3, 6, kernel_size=5)
    self.conv2 = nn.Conv2d(6, 12, kernel_size=3)
    self.conv3 = nn.Conv2d(12, 18, kernel_size=3)
    self.conv4 = nn.Conv2d(18, 24, kernel_size=3)
    self.fc1 = nn.Linear(4704, 1000)
    self.fc2 = nn.Linear(1000, 350)
    self.fc3 = nn.Linear(350,43)


def forward (self,x):
    x = F.relu(F.max_pool2d(self.conv1(x), 2))
    x = F.relu(F.max_pool2d(self.conv2(x), 2))
    x = F.relu(F.max_pool2d(self.conv3(x), 2))
    x = F.relu(F.max_pool2d(self.conv4(x), 2))
    x = x.view(-1,4704)
    x = F.relu(self.fc1(x))
    x = F.relu(self.fc2(x))
    x = self.fc3(x)
    return torch.sigmoid(x)



    # Traningsalgorithmus
optimizer = optim.Adam(model.parameters(), lr=0.001)
def train(epoch):
    model.train()
    batch_id = 0
    for data, target in train_data_set:
        data = Variable(data)
        target = torch.Tensor(target)
        target = Variable(target)
        optimizer.zero_grad()
        out = model(data)
        criterion = F.binary_cross_entropy
        loss = criterion(out,target)
        loss.backward()
        optimizer.step()
        print ('Train Epoch: {} [{}/{} ({:.0f}%)]\tLoss: {:.6f}'.format(
            epoch, batch_id * len(data), len(train_data_set)*32,
                100. * batch_id / len(train_data_set), loss.item()))
        batch_id = batch_id + 1


When i change the size of the Image to 50*50 and i change the code Net like this: 

class Netz(nn.Module):
def __init__(self):
    super(Netz,self).__init__()
    self.conv1 = nn.Conv2d(3, 6, kernel_size=5)
    self.conv2 = nn.Conv2d(6, 12, kernel_size=3)
    self.conv3 = nn.Conv2d(12, 18, kernel_size=3)
    self.conv4 = nn.Conv2d(18, 24, kernel_size=3)
    self.fc1 = nn.Linear(768, 1000)
    self.fc2 = nn.Linear(1000, 350)
    self.fc3 = nn.Linear(350,43)


def forward (self,x):
    x = F.relu(F.max_pool2d(self.conv1(x), 2))
    x = F.relu(F.max_pool2d(self.conv2(x), 2))
    x = F.relu(F.max_pool2d(self.conv3(x), 2))
    x = F.relu(F.max_pool2d(self.conv4(x), 2))
    x = x.view(-1,768)
    x = F.relu(self.fc1(x))
    x = F.relu(self.fc2(x))
    x = self.fc3(x)
    return torch.sigmoid(x)


I gonne get the error: 
ValueError: Target and input must have the same number of elements. target nelement (1376) != input nelement (43)

So far i see it the problem comes after the x = x.view(-1,768) it returns an Tensor with the torch.Size ([1,768]). When i use the Image Size 256*256 it returns Tensor with torch.Size ([32,4704]) and i don't get the error. 

Does someone know how i can fix me problem ? 

You need to be careful when using -1 in views, since it just uses the remaining size and if that doesn't correspond to your intentions, you won't immediately know that it didn't behave as expected. You should particularly avoid -1 for the batch dimension, because you can mistakenly change the batch size, which should not change and their data should be independent from each other.

Given an input of size [32, 3, 256, 256] the output after the convolutions has size [32, 24, 14, 14], which can be flattened to [32, 4704], as you anticipated in the first version. When you change the input to size [32, 3, 50, 50], the output after the convolutions has size [32, 24, 1, 1], which can clearly not be converted to size [32, 768], because flattening it, would result in a size of [32, 24]. Given that 32 * 24 = 768, you incorrectly combine the batches into one, creating a tensor of size [1, 768], and if you had used a different batch size, it wouldn't even work.

The correct input size to the first linear should be 24:

self.fc1 = nn.Linear(24, 1000)


To catch any mistake regarding the dimensions in the model, instead of later at the loss calculation, you can set the actual size without any -1 in the view, or alternatively flatten it after the batch size, either with view or torch.flatten, so an error will occur if there is a size mismatch in the linear layer:

# Reshape to [batch_size, 24]
x = x.view(x.size(0), 24)

# Flatten with view
x = x.view(x.size(0), -1)

# Flatten, starting from dimension 1 (after the batch dimension)
x = x.flatten(1)

