Pytorch, 预训练模型:如何同时使用特征提取和分类器

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

我的代码如下:

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

但我只能从最后一层获取111000的向量。

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

仅使用分类器:

use classifier only

仅使用特征提取:

use feathers only

同时使用它们:

use them at the same time

日志:

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'

回答:

我自己找到了解决方案。

抱歉打扰Stack Overflow了。

这是解决方案的代码:

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

结果如下:

enter image description here

我认为这是正确的答案。

Related Posts

使用LSTM在Python中预测未来值

这段代码可以预测指定股票的当前日期之前的值,但不能预测…

如何在gensim的word2vec模型中查找双词组的相似性

我有一个word2vec模型,假设我使用的是googl…

dask_xgboost.predict 可以工作但无法显示 – 数据必须是一维的

我试图使用 XGBoost 创建模型。 看起来我成功地…

ML Tuning – Cross Validation in Spark

我在https://spark.apache.org/…

如何在React JS中使用fetch从REST API获取预测

我正在开发一个应用程序,其中Flask REST AP…

如何分析ML.NET中多类分类预测得分数组?

我在ML.NET中创建了一个多类分类项目。该项目可以对…

发表回复

您的邮箱地址不会被公开。 必填项已用 * 标注