我想从我微调后的AlexNet的fc7
层提取4096
维的特征向量。我的目标是稍后使用这一层进行聚类。我的提取方法如下:
alexnet = models.alexnet(pretrained=True);fc7 = alexnet.classifier[6];
然而,当我打印时,fc7
是一个Linear
对象:
Linear(in_features=4096, out_features=1000, bias=True)
我想要的是如何将这个Linear
对象转换为numpy数组,以便我可以对其进行进一步的操作。我在考虑调用它的方法'def forward(self, input)'
,但不确定应该提供什么输入?我应该提供输入图像还是fc6
层的输出?
而且我想得到4096
维的输入数组,并去掉1000
维的输出数组(推测如此,因为我认为它对聚类没有帮助)。
回答:
这可以通过创建一个新的模型来实现,该模型具有与alexnet
相同的层(及其相关参数),但不包括最后一层。
new_model = models.alexnet(pretrained=True)new_classifier = nn.Sequential(*list(new_model.classifier.children())[:-1])new_model.classifier = new_classifier
现在,您应该能够将输入图像提供给new_model
并提取一个4096维的特征向量。
如果您确实需要将某个特定层作为numpy数组使用,您可以执行以下操作:fc7.weight.data.numpy()
。
(在PyTorch 0.4.0版本上)