MNIST Error Mismatch

I am running a 2 layer CNN on the MNIST dataset and I am getting this error.

RuntimeError: size ‘[-1 x 3136]’ is invalid for input of with 131072 elements at /py/conda-bld/pytorch_1490979338030/work/torch/lib/TH/THStorage.c:55

Model used

class Net(nn.Module):
    def __init__(self):
        super(Net, self).__init__()
        self.conv1 = nn.Conv2d(1, 32, 3, padding=2)
        # conv1 = 28x28x1 => 28x28x32
        # pooling = 28x28x32 => 14x14x32
        
        self.conv2 = nn.Conv2d(32, 64, 3, padding=2)
        # conv2 = 14x14x32 => 14x14x64
        # pooling = 14x14x64 => 7x7x64
        
        self.fc1 = nn.Linear(64*7*7, 1024)
        self.fc2 = nn.Linear(1024, 10)
        
    def forward(self, x):
        x = F.max_pool2d(F.relu(self.conv1(x)), 2)
        x = F.max_pool2d(F.relu(self.conv2(x)), 2)
        # reshape Variable
        x = x.view(-1, 64*7*7) 
        x = F.relu(self.fc1(x))
        x = F.dropout(x, training=self.training)
        x = self.fc2(x)
        return x

Can anyone tell me what am I doing wrong?

the expected input to this network is of size 28x28 images (batch x 1 x 28 x 28), but you are giving larger images.

Hence, at x = x.view(-1, 64*7*7) this operation is failing.

@smth his network works fine when the kernel_size = 5. What does the kernel_size mean? Is it the size of filter?

yes its the size of the filter. read the docs.

Solved the error. Added x.size() before the Linear layer in the forward function to get the size. Simple hack :slight_smile: