【问题标题】:Fine-tuning Resnet using pre-convoluted features使用预卷积特征微调 Resnet
【发布时间】:2020-07-23 14:51:53
【问题描述】:

我们知道卷积层的计算成本很高,我想计算一次卷积层的输出,并用它们来训练我的 Resnet 的全连接层,以加快处理速度。

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

x = model_vgg.features(inputs)

但是如何从 Resnet 中提取特征?

提前致谢

【问题讨论】:

  • 假设您谈论的是torchvision.models 的 ResNet,那么您无法开箱即用地提取特征。您必须实现该方法(开源项目很棒:))或将类扩展为实现它的类。

标签: pytorch resnet vgg-net


【解决方案1】:

我想你可以尝试通过网络进行黑客攻击。我以 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.

【讨论】:

  • 非常感谢!我所做的只是删除 fc 层 conv_layers = list(model_resnet.children())[:-1] model = nn.Sequential(*conv_layers) for param in model.parameters(): param.requires_grad = False
  • 哦,那也不错。但是如果你把它们都放在Sequential中,resnet的剩余块/跳过连接事情还会发生吗?我认为该机制是在 forward() 方法中实现的。
猜你喜欢
  • 1970-01-01
  • 2020-12-02
  • 2017-06-17
  • 2012-01-12
  • 2019-06-19
  • 1970-01-01
  • 2019-07-21
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多