【发布时间】: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