背景:
我正在研究一种对抗性检测器方法,它需要访问每个隐藏层的输出。
我从torchvision.models
加载了一个预训练的VGG16
为了访问每个隐藏层的输出,我将其放入一个顺序模型中:
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()
,forward方法将抱怨mat1
和mat2
之间的维度不匹配
我研究了torchvisionVGG实现,它使用了[feature..., AvgPool, flatten, classifier...]
结构。
由于AdaptiveAvgPool2d
层和Flatten
层没有参数,我假设这应该可以工作,但我有不同的输出
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])
False
我在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
有人能指出哪里出了问题吗? 多谢各位
在进行推断之前,需要调用eval模式
即
相关问题 更多 >
编程相关推荐