运行时错误:mat1和mat2形状无法在pytorch中相乘

Sho*_*na 3 python artificial-intelligence deep-learning pytorch

我是深度学习的新手,我使用下面的代码创建了一个模型来预测植物病害

class CNN_Model(nn.Module):
  def __init__(self):
    super(CNN_Model, self).__init__()
    self.cnn_model = nn.Sequential(
        nn.Conv2d(3, 16, 3),    
        nn.ReLU(),
        nn.MaxPool2d(2, 2),     
        nn.Conv2d(16, 32, 5),   
        nn.ReLU(),
        nn.MaxPool2d(2, 2),     
    )

    self.fc_model = nn.Sequential(
        nn.Flatten(),           
        nn.Linear(800, 300),    
        nn.ReLU(),
        nn.Linear(300, 38),     
        nn.Softmax(dim=1)
    )

  def forward(self, x):
      x = self.cnn_model(x)
      x = self.fc_model(x)

      return x
Run Code Online (Sandbox Code Playgroud)
model = CNN_Model()

out = model(imgs)
out
Run Code Online (Sandbox Code Playgroud)

当我尝试运行上面的代码时,出现错误 mat1 和 mat2 无法相乘。我已经尝试过针对类似问题发布的答案,但我的问题仍然没有解决。

RuntimeError                              Traceback (most recent call last)
/tmp/ipykernel_66/1768380315.py in <module>
----> 1 out = model(imgs)
      2 out

/opt/conda/lib/python3.7/site-packages/torch/nn/modules/module.py in _call_impl(self, *input, **kwargs)
   1049         if not (self._backward_hooks or self._forward_hooks or self._forward_pre_hooks or _global_backward_hooks
   1050                 or _global_forward_hooks or _global_forward_pre_hooks):
-> 1051             return forward_call(*input, **kwargs)
   1052         # Do not call functions when jit is used
   1053         full_backward_hooks, non_full_backward_hooks = [], []

/tmp/ipykernel_66/1577403502.py in forward(self, x)
     26   def forward(self, x):
     27       x = self.cnn_model(x)
---> 28       x = self.fc_model(x)
     29 
     30       return x

/opt/conda/lib/python3.7/site-packages/torch/nn/modules/module.py in _call_impl(self, *input, **kwargs)
   1049         if not (self._backward_hooks or self._forward_hooks or self._forward_pre_hooks or _global_backward_hooks
   1050                 or _global_forward_hooks or _global_forward_pre_hooks):
-> 1051             return forward_call(*input, **kwargs)
   1052         # Do not call functions when jit is used
   1053         full_backward_hooks, non_full_backward_hooks = [], []

/opt/conda/lib/python3.7/site-packages/torch/nn/modules/container.py in forward(self, input)
    137     def forward(self, input):
    138         for module in self:
--> 139             input = module(input)
    140         return input
    141 

/opt/conda/lib/python3.7/site-packages/torch/nn/modules/module.py in _call_impl(self, *input, **kwargs)
   1049         if not (self._backward_hooks or self._forward_hooks or self._forward_pre_hooks or _global_backward_hooks
   1050                 or _global_forward_hooks or _global_forward_pre_hooks):
-> 1051             return forward_call(*input, **kwargs)
   1052         # Do not call functions when jit is used
   1053         full_backward_hooks, non_full_backward_hooks = [], []

/opt/conda/lib/python3.7/site-packages/torch/nn/modules/linear.py in forward(self, input)
     94 
     95     def forward(self, input: Tensor) -> Tensor:
---> 96         return F.linear(input, self.weight, self.bias)
     97 
     98     def extra_repr(self) -> str:

/opt/conda/lib/python3.7/site-packages/torch/nn/functional.py in linear(input, weight, bias)
   1845     if has_torch_function_variadic(input, weight):
   1846         return handle_torch_function(linear, (input, weight), input, weight, bias=bias)
-> 1847     return torch._C._nn.linear(input, weight, bias)
   1848 
   1849 

RuntimeError: mat1 and mat2 shapes cannot be multiplied (32x119072 and 800x300)
Run Code Online (Sandbox Code Playgroud)

请有人帮助我解决这些错误。

Iva*_*van 13

尺寸不匹配误差如图所示32x119072 and 800x300。第一个形状是指输入张量,第二个形状是层的参数。如果您查看模型定义,您会发现它与第一个完全连接的层(即扁平化之后的层)匹配。事实上,nn.Linear(800, 300)本来期待800-feature 张量,但得到119072-feature 张量。

您需要修改此线性层以匹配传入的张量展平空间形状。但请注意该值将如何取决于输入 CNN 的图像,最终这将决定输入分类器的张量的大小。解决这个问题的一般方法是使用自适应层:例如无论nn.AdaptiveMaxPool2d输入维度大小如何,自适应层都将始终提供相同的输出形状。

  • 我说你的代码有什么问题。请花一些时间来理解答案,只有这样你才能找到问题所在。*确实,nn.Linear(800, 300) 期望有 800 个特征张量,但得到的是 119072 个特征张量。*...您有什么需要更改的吗? (16认同)