我正在实现一个线性自动编码器,在这里我馈送尺寸为(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
的输入大小,但我仍然得到了形状错误——不明白我做错了什么。
如果我理解你的代码,你给神经的输入是784,但你给它28试着像这个一样改变这条线
self.enc1 = nn.Linear(in_features=28, out_features=256)
self.dec5 = nn.Linear(in_features=256, out_features=28)