背景:我正在研究一种对抗检测器方法,该方法需要访问每个隐藏层的输出。我从加载了预训练的VGG16 torchvision.models
。
要访问每个隐藏层的输出,我将其放入顺序模型中:
vgg16 = models.vgg16(pretrained=True)
vgg16_seq = nn.Sequential(*(
list(list(vgg16.children())[0]) +
[nn.AdaptiveAvgPool2d((7, 7)), nn.Flatten()] +
list(list(vgg16.children())[2])))
如果没有nn.Flatten()
,前向方法将抱怨mat1
和之间的尺寸不匹配mat2
。
我研究了torchvision VGG的实现,它使用了[feature..., AvgPool, flatten, classifier...]
结构。由于AdaptiveAvgPool2d
layer和Flatten
layer没有参数,因此我认为这应该起作用,但是我有不同的输出。
output1 = vgg16(X_small)
print(output1.size())
output2 = vgg16_seq(X_small)
print(output2.size())
torch.equal(output1, output2)
问题:它们的尺寸相同,但输出却不同。
torch.Size([32,1000])
torch.Size([32,1000])
错误
我在AdaptiveAvgPool2d
层之后测试了输出,输出相等:
output1 = nn.Sequential(*list(vgg16.children())[:2])(X_small)
print(output1.size())
output2 = nn.Sequential(*list(vgg16_seq)[:32])(X_small)
print(output2.size())
torch.equal(output1, output2)
torch.Size([32,512,7,7])
torch.Size([32,512,7,7])
True
有人可以指出出了什么问题吗?谢谢
您需要在进行推断之前调用评估模式。
即
vgg16.eval()
vgg16_seq.eval()
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句