【问题标题】:Getting error with two matrices multiplication (mat1 and mat2 shapes cannot be multiplied)两个矩阵相乘时出错(mat1 和 mat2 形状不能相乘)
【发布时间】:2021-06-24 16:08:25
【问题描述】:

为我的网络运行训练过程后出现以下错误。

RuntimeError: mat1 和 mat2 形状不能相乘(21760x17 和 18496x512)

这是网络架构

self.layer1 = nn.Sequential(
    nn.Conv2d(3, 16, kernel_size=3),
    nn.ReLU(),
    nn.MaxPool2d(2)
)

self.layer2 = nn.Sequential(
    nn.Conv2d(16, 32, kernel_size=3),
    nn.ReLU(),
    nn.MaxPool2d(2)
)

self.layer3 = nn.Sequential(
    nn.Conv2d(32, 64, kernel_size=3),
    nn.ReLU(),
    nn.MaxPool2d(2)
)

self.flatten = nn.Flatten(2)
self.fc1 = nn.Linear(18496, 512)
self.fc2 = nn.Linear(512,1)
self.sigmoid = nn.Sigmoid()


def forward(self, x):
  x = self.layer1(x)
  x = self.layer2(x)
  x = self.layer3(x)
  x = self.fc1(x)
  x = self.fc2(x)
  return x

输入尺寸的图像为 150x150x3。是什么导致了这个问题?

编辑:

架构基于在 Keras 中创建的模型。我需要从 Keras 转换为 Pytorch。

基于此,我创建了如上所示的网络。

【问题讨论】:

  • 您好,请阅读stackoverflow.com/help/minimal-reproducible-example。您需要提供您在 NN 中输入的张量,因为您输入的形状很可能与您的模型的定义不兼容 :)
  • 写出您的逻辑可能会有所帮助,即为什么您希望扁平输出的形状为 18496?
  • @DerekG,我添加了一些额外的解释。
  • 好的,所以在每一层之后打印形状,看看哪些操作导致输出的大小与您预期的不同

标签: python pytorch


【解决方案1】:

我已经通过更改转发方法解决了这个问题:

def forward(self,x):        
   out = self.layer1(x)        
   out = self.layer2(out)        
   out = self.layer3(out)        
   out = out.view(out.size(0),-1)        
   out = self.relu(self.fc1(out))        
   out = self.fc2(out)       
   out = torch.sigmoid(out)        
   return out

【讨论】:

    猜你喜欢
    • 2021-05-25
    • 2021-09-09
    • 2021-09-23
    • 2022-07-15
    • 2023-01-28
    • 1970-01-01
    • 2021-09-17
    • 2022-08-22
    • 1970-01-01
    相关资源
    最近更新 更多