我正在尝试实现一个基于卷积层和最大池的自动编码器神经网络;对灰度图像(MNIST图像(进行编码和解码。我将其类别ConvAEUnpool
定义如下:
class ConvAEUnpool(nn.Module):
def __init__(self):
super(ConvAEUnpool, self).__init__()
self.relu = nn.ReLU()
self.sigmoid = nn.Sigmoid()
#Coder
self.conv1 = nn.Conv2d(1, 16, 3, stride=3, padding=1), # b, 16, 10, 10
self.maxPool1 = nn.MaxPool2d(2, stride=2, return_indices=True), # b, 16, 5, 5
self.conv2 = nn.Conv2d(16, 8, 3, stride=2, padding=1), # b, 8, 3, 3
self.maxPool2 = nn.MaxPool2d(2, stride=1, return_indices=True) # b, 8, 2, 2
# Decoder
self.maxUnpool1 = nn.MaxUnpool2d(2, stride=1) # b, 8, 3, 3
self.deConv1 = nn.ConvTranspose2d( 8, 16, 3, stride=2), # b, 16, 5, 5
self.maxUnpool2 = nn.MaxUnpool2d(2, stride=2) # b, 16, 10, 10
self.deConv2 = nn.ConvTranspose2d(16, 1, 3, stride=3, padding=1), # b, 1, 28, 28
def forward(self, x):
# Code
x = self.Conv1(x)
x = self.relu(x)
x, idx1 = self.MaxPool1(x)
x = self.Conv2(x)
x = self.relu(x)
x, idx2 = self.MaxPool2(x)
# Decode
x = self.MaxUnpool1(x, idx2)
x = self.DeConv1(x)
x = self.MaxUnpool2(x, idx1)
x = self.DeConv2(x)
x = self.sigmoid(x)
return x
出于某种原因,当我创建一个实例并尝试为其参数选择优化器时,如下所示:
model = ConvAEUnpool().to(device)
# create an optimizer object
optimizer = torch.optim.Adam(model.parameters(), lr=1e-3)
则会引发以下错误:ValueError:优化器得到一个空的参数列表
我已经做了一些搜索,并尝试使用nn。ModuleList((:
self.nn_layers = nn.ModuleList(modules=[self.Conv1, self.MaxPool1, self.Conv2, self.MaxPool2,
self.MaxUnpool1, self.DeConv1, self.MaxUnpool2, self.DeConv2])
但我不确定如何使用MaxUnpool2d,因为我需要传递上一个MaxPool2d层的索引。有人能帮我吗?
在__init__
方法中,在大多数指令的末尾都添加了逗号(','(。移除它们,model.parameters()
将正常工作