Pytorch 使用预卷积特征微调Resnet

Pytorch 使用预卷积特征微调Resnet,pytorch,resnet,vgg-net,Pytorch,Resnet,Vgg Net,因为我们知道卷积层的计算成本很高,所以我想计算一次卷积层的输出,并使用它们来训练我的Resnet的完全连接层,以加速这个过程 在VGG模型的情况下,我们可以计算第一个卷积部分的输出,如下所示 x = model_vgg.features(inputs) 但是如何从Resnet中提取特征呢 提前谢谢我想你可以尝试通过网络进行黑客攻击。我将以resnet18为例: import torch from torch import nn from torchvision.models import re

因为我们知道卷积层的计算成本很高,所以我想计算一次卷积层的输出,并使用它们来训练我的Resnet的完全连接层,以加速这个过程

在VGG模型的情况下,我们可以计算第一个卷积部分的输出,如下所示

x = model_vgg.features(inputs)
但是如何从Resnet中提取特征呢


提前谢谢

我想你可以尝试通过网络进行黑客攻击。我将以resnet18为例:

import torch
from torch import nn
from torchvision.models import resnet18

net = resnet18(pretrained=False)
print(net)
您将看到如下内容:

....
      (conv2): Conv2d(512, 512, kernel_size=(3, 3), stride=(1, 1), padding=(1, 1), bias=False)
      (bn2): BatchNorm2d(512, eps=1e-05, momentum=0.1, affine=True, track_running_stats=True)
    )
  )
  (avgpool): AdaptiveAvgPool2d(output_size=(1, 1))
  (fc): Linear(in_features=512, out_features=1000, bias=True)
让我们将线性层存储在某个地方,并在其位置放置一个虚拟层。那么整个网络的输出实际上就是conv层的输出

x = torch.randn(4,3,32,32) # dummy input of batch size 4 and 32x32 rgb images
out = net(x)
print(out.shape)
>>> 4, 1000 # batch size 4, 1000 default class predictions

store_fc = net.fc      # Save the actual Linear layer for later
net.fc = nn.Identity() # Add a layer which actually does nothing
out = net(x)
print(out.shape)
>>> 4, 512 # batch size 4, 512 features that are the input to the actual fc layer.

假设您正在谈论的是
torchvision.models
的ResNet,那么您无法从盒子中提取特征。您必须实现该方法(开源项目非常棒:),或者将该类扩展到实现它的类。非常感谢!我所做的只是删除了模型中参数的fc层
conv\u layers=list(model\u resnet.children())[:-1]
model=nn.Sequential(*conv\u layers)
对于模型中的参数()。但是如果你把它们都按顺序排列,resnet的剩余阻塞/跳过连接的事情还会发生吗?我认为该机制是在forward()方法中实现的。