我是pytorch的新手,所以我需要一点抓握。我试图重用一个旧的CNN分类模型——重用已经训练好的卷积层作为自动编码器中的编码器,然后训练解码器层。下面的代码就是我所拥有的。
class Autoencoder(nn.Module):
def __init__(self, model, specs):
super(Autoencoder, self).__init__()
self.encoder = nn.Sequential(
*list(model.conv_layer.children())
)
self.decoder = nn.Sequential(
nn.ConvTranspose2d(in_channels=C7, out_channels=C6, kernel_size=pooling, padding=0),
nn.ReLU(inplace=True),
nn.ConvTranspose2d(in_channels=C6, out_channels=C5, kernel_size=pooling, padding=0),
nn.ReLU(inplace=True),
nn.ConvTranspose2d(in_channels=C5, out_channels=C4, kernel_size=pooling, padding=0),
nn.ReLU(inplace=True),
nn.ConvTranspose2d(in_channels=C4, out_channels=C3, kernel_size=pooling, padding=0),
nn.ReLU(inplace=True),
nn.ConvTranspose2d(in_channels=C3, out_channels=C2, kernel_size=pooling, padding=0),
nn.ReLU(inplace=True),
nn.ConvTranspose2d(in_channels=C2, out_channels=C1, kernel_size=pooling, padding=0),
nn.ReLU(inplace=True),
nn.ConvTranspose2d(in_channels=C1, out_channels=C0, kernel_size=pooling, padding=0),
nn.ReLU(inplace=True),
nn.ConvTranspose2d(in_channels=C0, out_channels=3, kernel_size=pooling, padding=0),
nn.ReLU(inplace=True),
)
for param in self.encoder.parameters():
param.requires_grad = False
for p in self.decoder.parameters():
if p.dim() > 1:
nn.init.kaiming_normal_(p)
pass
def forward(self, x):
x = self.encoder(x)
x = self.decoder(x)
return x
但是,我得到了一个"NotImplementedError"。我做错了什么?当我启动该类的一个实例时,我将传递预先训练的CNN分类模型,self-encoder应该负责从模型中获取我感兴趣的层(conv_layer中的层(。当I:
model = pretrainedCNNmodel
autoencoder = Autoencoder(model, specs)
print(autoencoder)
打印看起来还可以,它有所有的层和我希望的一切,但当我尝试在上面训练时,我会得到"NotImplementedError:"。
编辑
以下是整个错误:
---------------------------------------------------------------------------
NotImplementedError Traceback (most recent call last)
<ipython-input-20-9adc467b2472> in <module>()
2 optimizer = torch.optim.Adam(model.parameters(), lr=learning_rate, weight_decay=L2_lambda)
3
----> 4 train(x, train_loader, test_loader, optimizer, criterion)
2 frames
<ipython-input-5-b25edb14cf5f> in train(model, train_loader, test_loader, optimizer, criterion)
15 data, target = data.cuda(), target.cuda()
16 optimizer.zero_grad()
---> 17 output = model(data)
18 loss = criterion(output, target)
19 loss.backward()
/usr/local/lib/python3.6/dist-packages/torch/nn/modules/module.py in __call__(self, *input, **kwargs)
530 result = self._slow_forward(*input, **kwargs)
531 else:
--> 532 result = self.forward(*input, **kwargs)
533 for hook in self._forward_hooks.values():
534 hook_result = hook(self, input, result)
/usr/local/lib/python3.6/dist-packages/torch/nn/modules/module.py in forward(self, *input)
94 registered hooks while the latter silently ignores them.
95 """
---> 96 raise NotImplementedError
97
98 def register_buffer(self, name, tensor):
NotImplementedError:
由于您在这个问题上有赏金,所以无法关闭。然而,完全相同的问题已经在这个线程中被问到并回答了。
基本上,您的代码中存在缩进问题:forward
方法被缩进,因此它位于__init__
方法的内部,而不是Autoencoder
类的一部分。
有关更多详细信息,请参阅我的另一个答案。