pytorch搭建cnn报错:RuntimeError: size mismatch, m1: [10 x 43264], m2: [10816 x 2] at C...

具体报错信息:

Traceback (most recent call last):
  File "E:/Program Files/PyCharm 2019.2/machinelearning/homework/CNN.py", line 172, in <module>
    train()
  File "E:/Program Files/PyCharm 2019.2/machinelearning/homework/CNN.py", line 147, in train
    output = model(data)[0]
  File "F:\Anaconda3\lib\site-packages\torch\nn\modules\module.py", line 550, in __call__
    result = self.forward(*input, **kwargs)
  File "E:/Program Files/PyCharm 2019.2/machinelearning/homework/CNN.py", line 131, in forward
    output = self.output(temp)
  File "F:\Anaconda3\lib\site-packages\torch\nn\modules\module.py", line 550, in __call__
    result = self.forward(*input, **kwargs)
  File "F:\Anaconda3\lib\site-packages\torch\nn\modules\linear.py", line 87, in forward
    return F.linear(input, self.weight, self.bias)
  File "F:\Anaconda3\lib\site-packages\torch\nn\functional.py", line 1610, in linear
    ret = torch.addmm(bias, input, weight.t())
RuntimeError: size mismatch, m1: [10 x 43264], m2: [10816 x 2] at C:/w/b/windows/pytorch/aten/src\THC/generic/THCTensorMathBlas.cu:283

原因:搭建cnn时最后一层卷积然后池化之后的输出大小与最后的全连接层输出大小不匹配。

解决办法:

def forward(self, x):
    x = self.conv1(x)
    x = self.conv2(x)
    x = self.conv3(x)
    print(x.size())
    temp = x.view(x.shape[0], -1)
    output = self.output(temp)
    return output, x

在最后一层卷积之后,输出x的size,然后在全连接层中做出相应更正。

你可能感兴趣的:(pytorch,DL,卷积,pytorch)