0

I get this error message and I'm not sure why. My input is (batch, 1, 312) from tabular data and this CNN is constructed for a regression prediction. I worked out the shapes for each step with the formula (input + 2*padding - filter size)/stride + 1 as in the comment below. The problem appears to occur at x = self.fc(x) and I can't figure out why. Your help is greatly appreciated. Thank you.

class CNNWeather(nn.Module):
    # input (batch, 1, 312)
    def __init__(self):
        super(CNNWeather, self).__init__()
        self.conv1 = nn.Conv1d(in_channels=1, out_channels=8, kernel_size=9, stride=1, padding='valid')         # (312+2*0-9)/1 + 1 = 304
        self.pool1 = nn.AvgPool1d(kernel_size=2, stride=2)                                                      # 304/2 = 302
        self.conv2 = nn.Conv1d(in_channels=8, out_channels=12, kernel_size=3, stride=1, padding='valid')        # (302-3)/1+1 = 300
        self.pool2 = nn.AvgPool1d(kernel_size=2, stride=2)                                                      # 300/2 = 150
        self.conv3 = nn.Conv1d(in_channels=12, out_channels=16, kernel_size=3, stride=1, padding='valid')       # (150-3)/1+1 = 76
        self.pool3 = nn.AvgPool1d(kernel_size=2, stride=2)                                                      # 76/2 = 38
        self.conv4 = nn.Conv1d(in_channels=16, out_channels=20, kernel_size=3, stride=1, padding='valid')       # (38-3)/1+1 = 36
        self.pool4 = nn.AvgPool1d(kernel_size=2, stride=2)                                                      # 36/2 = 18  (batch, 20, 18)
        self.fc = nn.Linear(in_features=20*18, out_features=1)

    def forward(self, x):
        x = self.pool1(F.relu(self.conv1(x)))
        x = self.pool2(F.relu(self.conv2(x)))
        x = self.pool3(F.relu(self.conv3(x)))
        x = self.pool4(F.relu(self.conv4(x)))
        print(x.size())
        x = x.view(x.size(0), -1)               # flatten   (batch, 20*18)
        x = self.fc(x)
        return x
0

1 Answer 1

1

The problem seems to be related to the input size of your FC layer:

self.fc = nn.Linear(in_features=20*18, out_features=1)

The output of the previous layer is 340, so you must use in_features=340.

These are the shapes of the output for the third and fourth layers.

torch.Size([5, 16, 73]) conv3 out
torch.Size([5, 16, 36]) pool3 out
torch.Size([5, 20, 34]) conv4 out
torch.Size([5, 20, 17]) pool4 out

Notice that out of the "pool4" layer come 20x17, meaning 340 elements.

1
  • 1
    Thank you very much. Double checked my calculations and I made a simple math error at 304/2.
    – Andy
    Mar 10, 2022 at 12:07

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

Not the answer you're looking for? Browse other questions tagged or ask your own question.