Pytorch获取VGG中间层的输出结果

获取VGG中间层的输出结果VGG结构VGG的结构根据其网络层数的深度,分为四种,分别为11,13,16,19.这四种对应的网络结构的配置的声明见下。defaultcfg = { 11 : [64, 'M', 128, 'M', 256, 256, 'M', 512, 512, 'M', 512, 512], 13 : [64, 64, 'M', 128, 128, 'M', 256, 256, 'M', 512, 512, 'M', 512, 512], 16 : [64,
摘要由CSDN通过智能技术生成

获取VGG中间层的输出结果

VGG结构

VGG的结构根据其网络层数的深度,分为四种,分别为11,13,16,19.这四种对应的网络结构的配置的声明见下。


defaultcfg = {
   
    11 : [64, 'M', 128, 'M', 256, 256, 'M', 512, 512, 'M', 512, 512],
    13 : [64, 64, 'M', 128, 128, 'M', 256, 256, 'M', 512, 512, 'M', 512, 512],
    16 : [64, 64, 'M', 128, 128, 'M', 256, 256, 256, 'M', 512, 512, 512, 'M', 512, 512, 512],
    19 : [64, 64, 'M', 128, 128, 'M', 256, 256, 256, 256, 'M', 512, 512, 512, 512, 'M', 512, 512, 512, 512],
}

其具体的结构见下图。配置里面主要储存本层的对应的in_channels.
在这里插入图片描述

代码

因为VGG网络可以训练很多数据集,一般数据集的label的种类是不同的,这个时候我们需要做的就是改变最后一层的fc的weight的输出维度。也就是通过这句来声明最后的输出结果。其中num_classes代表的是这个数据集对应的label的种类数。

self.classifier = nn.Linear(cfg[-1], num_classes)

总体的代码思路是,先配置4种VGG对应的结构信息,然后通过make_layers进行构建网络。代码如下。

import math
import torch
import torch.nn as nn
from torch.autograd import Variable
__all__ = ['vgg']
defaultcfg = {
   
    11 : [64, 'M', 128, 'M', 256, 256, 'M', 512, 512, 'M', 512, 512],
    13 : [64, 64, 'M', 128, 128, 'M', 256, 256, 'M', 512, 512, 'M', 512, 512],
    16 : [64, 64, 'M', 128, 128, 'M', 256, 256, 256, 'M', 512, 512, 512, 'M', 512, 512, 512],
    19 : [64, 64, 'M', 128, 128, 'M', 256, 256, 256, 256
  • 2
    点赞
  • 15
    收藏
    觉得还不错? 一键收藏
  • 3
    评论
获取PyTorch中间层的输出,可以使用`register_forward_hook`方法。该方法可用于在网络的前向传递中注册回调函数,并在给定层次结构上获取中间输出。 以下是一个示例代码,展示如何获取名为`intermediate_layer_output`层的输出: ```python import torch.nn as nn class MyModel(nn.Module): def __init__(self): super(MyModel, self).__init__() self.layer1 = nn.Linear(10, 5) self.intermediate_layer = nn.Linear(5, 3) self.layer2 = nn.Linear(3, 1) def forward(self, x): x = self.layer1(x) x = torch.relu(x) x = self.intermediate_layer(x) x = torch.relu(x) x = self.layer2(x) return x model = MyModel() # 定义回调函数 def get_intermediate_layer_output(name): def hook(model, input, output): setattr(model, name, output) return hook # 注册回调函数 model.intermediate_layer.register_forward_hook(get_intermediate_layer_output('intermediate_layer_output')) # 输入数据并进行前向传递 x = torch.randn(1, 10) output = model(x) # 获取中间输出 intermediate_output = model.intermediate_layer_output ``` 在上述代码中,我们首先定义了一个名为`MyModel`的模型,并在其中定义了三个线性层。然后,我们定义了一个名为`get_intermediate_layer_output`的回调函数,该函数用于获取中间层的输出。我们使用`register_forward_hook`方法将回调函数注册到`intermediate_layer`层上。最后,我们输入数据并进行前向传递,然后使用`model.intermediate_layer_output`获取中间输出
评论 3
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值