Pytork:将VGG模型转换为顺序模型,但得到不同的输出

2024-09-27 00:22:13 发布

您现在位置:Python中文网/ 问答频道 /正文

背景: 我正在研究一种对抗性检测器方法,它需要访问每个隐藏层的输出。 我从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方法将抱怨mat1mat2之间的维度不匹配

我研究了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

有人能指出哪里出了问题吗? 多谢各位


Tags: sizenntorchseqlistsmallprintchildren

热门问题