首页 > 解决方案 > Pytorch,预训练模型:如何同时使用特征和分类器

问题描述

我正在使用 vgg16 提取图像特征向量。我想从倒数第二层获得 1 1 4096 向量。

我的代码:

def get_model():
    model = models.vgg16(pretrained=True)#.features[:].classifier[:4]
    model = model.eval()
    # model.cuda()  # send the model to GPU, DO NOT include this line if you haven't a GPU
    return model

但我只能从最后一层得到 1 1 1000 个向量。

我知道如何使用feathersclassifier,但我不知道如何同时使用它们。

仅使用分类器:

仅使用分类器

仅使用羽毛:

只使用羽毛

同时使用它们:

同时使用它们

日志:

Traceback (most recent call last):
  File "/mnt/c/Users/sunji/PycharmProjects/image_cluster_pytorch/main.py", line 7, in <module>
    model = calc.get_model()
  File "/mnt/c/Users/sunji/PycharmProjects/image_cluster_pytorch/imagecluster/calc.py", line 17, in get_model
    model = models.vgg16(pretrained=True).features[:].classifier[:4]
  File "/usr/local/lib/python3.8/dist-packages/torch/nn/modules/module.py", line 771, in __getattr__
    raise ModuleAttributeError("'{}' object has no attribute '{}'".format(
torch.nn.modules.module.ModuleAttributeError: 'Sequential' object has no attribute 'classifier'

标签: machine-learningneural-networkpytorch

解决方案


我自己找到了解决方案。

很抱歉打扰堆栈溢出。

这是代码:

def get_model():
    model = models.vgg16(pretrained=True)
    model.features = model.features[:]
    model.classifier = model.classifier[:4]

    model = model.eval()
    # model.cuda()  # send the model to GPU, DO NOT include this line if you haven't a GPU
    return model

结果:

在此处输入图像描述

我认为这是正确的答案。


推荐阅读