【问题标题】:How to get a particular layer output of a pretrained VGG16 in pytorch如何在pytorch中获得预训练VGG16的特定层输出
【发布时间】:2020-03-19 08:02:33
【问题描述】:

我对 pytorch 非常陌生,我正在尝试以 1*4096 格式获取预训练模型 VGG16 特征向量的输出,该输出由最后一层之前的层返回。我发现 keras 中也有类似的功能。 pytorch中是否有相同的直接命令?

我正在使用的代码:

import torch
from torch import nn
from torch import optim
import torch.nn.functional as F
from torchvision import models
from torch.autograd import Variable
from PIL import Image

image1 = Image.open(r"C:\Users\user\Pictures\user.png")

model = models.vgg16(pretrained=True)

scaler = transforms.Resize((224, 224))
to_tensor = transforms.ToTensor()

img = to_tensor(scaler(image1)).unsqueeze(0)

model(img).shape
model(img)

【问题讨论】:

    标签: python computer-vision pytorch vgg-net


    【解决方案1】:

    负责创建features 的部分网络被命名为...features(不仅在 VGG 中,torchvision 中的大多数预训练网络都是如此)。

    只需使用此字段并像这样传递您的图像:

    import torch
    
    import torchvision
    
    image = Image.open(r"C:\Users\user\Pictures\user.png")
    
    # Get features part of the network
    model = models.vgg16(pretrained=True).features
    tensor = transforms.ToTensor()(transforms.Resize((224, 224))(image)).unsqueeze(dim=0)
    
    model(tensor)
    

    编辑:

    要查看任何torchvision 模型内部发生的情况,您可以查看它的源代码。对于 VGG (any),this file 的顶部有一个基类。

    要获得4096 扁平化特征,您可以进行类似于forward 中定义的操作:

    # Tensor from previous code snippet for brevity
    
    x = model.avgpool(tensor)
    x = torch.flatten(x, 1)
    final_x = model.classifier[0](x) # only first classifier layer
    

    您还可以遍历 moduleschildren 直到您想要的任何位置并输出结果(或结果或您想要的任何结果)

    【讨论】:

    • 对不起,如果我不够清楚。我试图在尺寸为 1 * 1000 的最终输出之前获得模型的输出。我想要在 1 * 4096 格式的最终​​层之前的输出。上面的方法会给我来自 torch.Size([1, 512, 7, 7]) 中的 features 模块的输出。
    • 你是这个意思吗?现在你会从预训练的VGG 得到(batch_size, 4096)
    • 谢谢。正是我想要的:)
    猜你喜欢
    • 2018-03-12
    • 2022-08-10
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-01-12
    • 2021-08-18
    • 2023-03-14
    • 2019-09-23
    相关资源
    最近更新 更多