【问题标题】:RuntimeError: mat1 and mat2 shapes cannot be multiplied (28x28 and 784x256)RuntimeError: mat1 和 mat2 形状不能相乘(28x28 和 784x256)
【发布时间】:2021-09-17 04:41:08
【问题描述】:

我正在实现一个线性自动编码器,我在其中输入大小为 (28,28) 的图像,但我收到 RuntimeError: mat1 and mat2 shapes cannot be multiplied (28x28 and 784x256) 错误

import torch.nn as nn
import torch.nn.functional as F
import torch
class Autoencoder(nn.Module):
    def __init__(self):
        super(Autoencoder, self).__init__()
        # encoder
        self.enc1 = nn.Linear(in_features=784, out_features=256)
        self.enc2 = nn.Linear(in_features=256, out_features=128)
        self.enc3 = nn.Linear(in_features=128, out_features=64)
        self.enc4 = nn.Linear(in_features=64, out_features=32)
        self.enc5 = nn.Linear(in_features=32, out_features=16)
        # decoder 
        self.dec1 = nn.Linear(in_features=16, out_features=32)
        self.dec2 = nn.Linear(in_features=32, out_features=64)
        self.dec3 = nn.Linear(in_features=64, out_features=128)
        self.dec4 = nn.Linear(in_features=128, out_features=256)
        self.dec5 = nn.Linear(in_features=256, out_features=784)
    def forward(self, x):
        x = F.relu(self.enc1(x))
        x = F.relu(self.enc2(x))
        x = F.relu(self.enc3(x))
        x = F.relu(self.enc4(x))
        x = F.relu(self.enc5(x))
        x = F.relu(self.dec1(x))
        x = F.relu(self.dec2(x))
        x = F.relu(self.dec3(x))
        x = F.relu(self.dec4(x))
        x = F.relu(self.dec5(x))
        return x
net = Autoencoder()
print(net)
Image = torch.randn(1,1,28,28)
net(Image)

我完美地给出了 28*28 = 784 的输入大小,但我仍然收到形状错误,不明白我在哪里做错了。

【问题讨论】:

  • 我不知道您在这里使用的库,但问题似乎是数学问题。将两个大小为 28x28 的矩阵乘以 784x256 是不可能的(内部尺寸必须匹配)。您应该分析堆栈跟踪以找出它正在尝试做什么。
  • @PMF 谢谢我在这里使用 pytorch
  • 我看到了,但正如我所说,我对那个库没有经验。但我知道它试图告诉你你试图做的数学运算是无效的。

标签: python deep-learning pytorch autoencoder


【解决方案1】:

如果我理解你的代码,你给神经的输入是 784,但你给它的是 28 尝试像这样更改此行

self.enc1 = nn.Linear(in_features=28, out_features=256)
self.dec5 = nn.Linear(in_features=256, out_features=28)

【讨论】:

  • 感谢它的帮助,但我的图像大小是 28,28 那么为什么线性层只占用 28 个神经元,但为什么不是 28*28 神经元?
  • 我不确定,但我认为您可以将其发送为 (28*28,28*28)
猜你喜欢
  • 2021-09-23
  • 2021-05-25
  • 2021-09-09
  • 1970-01-01
  • 1970-01-01
  • 2021-11-14
  • 2023-01-28
  • 2022-08-22
  • 1970-01-01
相关资源
最近更新 更多