Input Size Mismatch in CNN

Im trying to train my hand image dataset into CNN by following the MNIST CNN code given on github, but im getting input size mismatch error, So can anyone help me with this.

my Images are 3 channel 200x200 images
and number of classes = 32
and my mini batch size in dataloader class is 10

class CNN(nn.Module):
    def __init__(self):
        super(CNN, self).__init__()
        self.layer1 = nn.Sequential(
            nn.Conv2d(3, 16, kernel_size=5, padding=2),
            nn.BatchNorm2d(16),
            nn.ReLU(),
            nn.MaxPool2d(2))
        self.layer2 = nn.Sequential(
            nn.Conv2d(16, 32, kernel_size=5, padding=2),
            nn.BatchNorm2d(32),
            nn.ReLU(),
            nn.MaxPool2d(2))
        self.fc = nn.Linear(7*7*32, 10)
        
    def forward(self, x):
        out = self.layer1(x)
        out = self.layer2(out)
        out = out.view(out.size(0), -1)
        out = self.fc(out)
        return out

Where should i change in this code to get this working, right now im getting this input mismatch error

RuntimeError: size mismatch, m1: [10 x 80000], m2: [1568 x 10] at /Users/soumith/minicondabuild3/conda-bld/pytorch_1518371252923/work/torch/lib/TH/generic/THTensorMath.c:1434

Hi,

self.fc = nn.Linear(7*7*32, 10) did you recomputed these coeficient to fit your image size? I guess this is not 7*7*32 anymore?

yes this is where im confused , it was same in MNIST model , how do i change it according to my dataset ?

It should probably be 50*50*32.
You could add a print statement just before flattening x:

out = self.layer2(out)
print(out.shape)

Passing an input through the model you will get the right shape to use for your flattening.

1 Like