【问题标题】:RuntimeError: mat1 and mat2 shapes cannot be multiplied (1280x5 and 6400x4096)?RuntimeError:mat1 和 mat2 形状不能相乘(1280x5 和 6400x4096)?
【发布时间】:2021-12-03 14:37:04
【问题描述】:

使用下面的代码定义Alexnet,可以训练成功。但是当我想看每一层的输出时,会报错'RuntimeError: mat1 and mat2 shapes can be multiplied (1280x5 and 6400x4096)?'

class AlexNet(nn.Module):
    def __init__(self):
      super(AlexNet, self).__init__()
      self.conv = nn.Sequential(
          nn.Conv2d(1, 96, 11, 4),
          nn.ReLU(),
          nn.MaxPool2d(3, 2),
          nn.Conv2d(96, 256, 5, 1, 2),
          nn.ReLU(),
          nn.MaxPool2d(3, 2),
          nn.Conv2d(256, 384, 3, 1, 1),
          nn.ReLU(),
          nn.Conv2d(384, 384, 3, 1, 1),
          nn.ReLU(),
          nn.Conv2d(384, 256, 3, 1, 1),
          nn.ReLU(),
          nn.MaxPool2d(3, 2)
         )
      self.fc = nn.Sequential(
          nn.Linear(256*5*5, 4096),
          nn.ReLU(),
          nn.Dropout(0.5),
          nn.Linear(4096, 4096),
          nn.ReLU(),
          nn.Dropout(0.5),
          nn.Linear(4096, 10)
        )
      
    def forward(self, img):
      feature = self.conv(img)
      output = self.fc(feature.view(img.shape[0], -1))
      return output
X=torch.randn(1,1,224,224)
for name,layer in net.named_children():
  X=layer(X)
  print(name,X.shape)

你能帮帮我吗?

【问题讨论】:

    标签: matrix deep-learning pytorch conv-neural-network


    【解决方案1】:

    您忘记在 for 循环中展平 self.conv 的输出数组。你可以把它分成两个循环,一个用于卷积层,一个用于全连接层。

    
    X = torch.randn(1, 1, 224, 224)
    for name, layer in net.conv.named_children():
      X = layer(X)
      print(name, X.shape)
    
    X = X.flatten()  # or X = X.view(X.shape[0], -1)
    
    for name, layer in net.fc.named_children():
      X = layer(X)
      print(name, X.shape)
    

    【讨论】:

    • 你的做法绝对正确,谢谢!
    猜你喜欢
    • 2021-07-20
    • 2021-09-24
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2022-11-24
    • 2022-01-19
    • 1970-01-01
    • 2022-08-15
    相关资源
    最近更新 更多