yyyyy
yyyyy

Reputation: 3

Pytorch nn.Linear RuntimeError: mat1 dim 1 must match mat2 dim 0

class Net(nn.Module):
    def __init__(self):
        super().__init__()
        self.conv1 = nn.Conv2d(1, 16, 3, padding=1)
        self.conv2 = nn.Conv2d(16, 32, 3, padding=1)
        self.max_pool = nn.MaxPool2d(2)
        self.fc1 = nn.Linear(7*7*32, 128)
        self.fc1 = nn.Linear(128, 10)

    def forward(self, x):
        x = self.max_pool(F.relu(self.conv1(x)))
        x = self.max_pool(F.relu(self.conv2(x)))
        x = torch.flatten(x, 1)
        x = self.fc1(x)
        x = F.relu(x)
        x = self.fc2(x)
        x = F.softmax(x, dim=1)
        return x

The above is the model. The shape of input image is 1×28×28 with batch_size 16. I tried to print x.shape after flatten, which is (16, 1568), completely corresponding to the input size of self.fc1(). Does anyone have any idea?

Upvotes: 0

Views: 1959

Answers (1)

Prajot Kuvalekar
Prajot Kuvalekar

Reputation: 6618

you have named this function nn.Linear(128, 10) as self.fc1
i.e self.fc1 = nn.Linear(128, 10)
Please change it to self.fc2 = nn.Linear(128, 10)

Upvotes: 1

Related Questions