Pytorch源码学习之四:torchvision.models.squeezenet

2023-05-16

0.介绍

Squeezenet网址
torchvision.model.squeeze官方文档
主要思想:堆叠Fire模块,每个Fire模块,分别采用1x1和3x3两个分支,最后做拼;,每个Fire的尺寸不变,channel数不变或增加;每个stage的Fire模块之间用nn.MaxPool2d进行下采样;使用卷积层代替FC层,channel数为类别数

1.源码

import torch
import torch.nn as nn
import torch.nn.init as init
from torch.hub import load_state_dict_from_url

__all__ = ['SqueezeNet', 'squeezenet1_0', 'squeezenet1_1']
model_urls = {
    'squeezenet1_0': 'https://download.pytorch.org/models/squeezenet1_0-a815701f.pth',
    'squeezenet1_1': 'https://download.pytorch.org/models/squeezenet1_1-f364aa15.pth',
}

class Fire(nn.Module): #Fire模块
    def __init__(self, inplanes, squeeze_planes, expand1x1_planes, expand3x3_planes):

        super(Fire, self).__init__()
        self.inplanes = inplanes
        self.squeeze = nn.Conv2d(inplanes, squeeze_planes, kernel_size=1)
        self.squeeze_activation = nn.ReLU(inplace=True)
        self.expand1x1 = nn.Conv2d(squeeze_planes, expand1x1_planes, kernel_size=1)
        self.expand1x1_activation = nn.ReLU(inplace=True)
        self.expand3x3 = nn.Conv2d(squeeze_planes, expand3x3_planes, kernel_size=3, padding=1)
        self.expand3x3_activation = nn.ReLU(inplace=True)
    def forward(self, x):
        x = self.squeeze(x)
        x = self.squeeze_activation(x)
        return torch.cat([
            self.expand1x1_activation(self.expand1x1(x)),
            self.expand3x3_activation(self.expand3x3(x))
        ], 1)

class SqueezeNet(nn.Module):

    def __init__(self, version='1.0', num_classes=1000):
        super(SqueezeNet, self).__init__()
        self.num_classes = num_classes
        if version == '1_0':
            self.features = nn.Sequential(
                nn.Conv2d(3, 96, kernel_size=7, stride=2),
                nn.ReLU(inplace=True),
                nn.MaxPool2d(kernel_size=3, stride=2, ceil_mode=True),
                Fire(96, 16, 64, 64),
                Fire(128, 16, 64, 64),
                Fire(128, 32, 128, 128),
                nn.MaxPool2d(kernel_size=3, stride=2, ceil_mode=True),
                Fire(256, 32, 128, 128),
                Fire(256, 48, 192, 192),
                Fire(384, 48, 192, 192),
                Fire(384, 64, 256, 256),
                nn.MaxPool2d(kernel_size=3, stride=2 ,ceil_mode=True),
                Fire(512, 64, 256, 256),
            )
        elif version == '1_1':
            self.features = nn.Sequential(
                nn.Conv2d(3, 64, kernel_size=3, stride=2),
                nn.ReLU(inplace=True),
                nn.MaxPool2d(kernel_size=3, stride=2, ceil_mode=True),
                Fire(64, 16, 64, 64),
                Fire(128, 16, 64, 64),
                nn.MaxPool2d(kernel_size=3, stride=2, ceil_mode=True),
                Fire(128, 32, 128, 128),
                Fire(256, 32, 128, 128),
                nn.MaxPool2d(kernel_size=3, stride=2, ceil_mode=True),
                Fire(256, 48, 192, 192),
                Fire(384, 48, 192, 192),
                Fire(384, 64, 256, 256),
                Fire(512, 64, 256, 256),
            )
        else:
            raise ValueError("Unsupported SqueezeNet version {version}: 1_0 or 1_1 expected".format(version=version))
        #使用卷积代替全连接层
        final_conv = nn.Conv2d(512, self.num_classes, kernel_size=1)
        self.classifier = nn.Sequential(
            nn.Dropout(0.5),
            final_conv,
            nn.ReLU(inplace=True),
            nn.AdaptiveAvgPool2d((1,1))
        )
        for m in self.modules():
            if isinstance(m, nn.Conv2d):
                if m is final_conv:
                    init.normal_(m.weight, mean=0.0, std=0.01)
                else:
                    init.kaiming_uniform_(m.weight)
                if m.bias is not None:
                    init.constant_(m.bias, 0)
    def forward(self, x):
        x = self.features(x)
        x = self.classifier(x)
        return x.view(x.size(0), self.num_classes)

def _squeezenet(version, pretrained, progress, **kwargs):
    model = SqueezeNet(version, **kwargs)
    if pretrained:
        arch = 'squeezenet' + version
        state_dict = load_state_dict_from_url(model_urls[arch],
                                              progress=progress)
        model.load_state_dict(state_dict)
    return model

def squeezenet1_0(pretrained=False, progress=True, **kwargs):
    return _squeezenet('1_0', pretrained, progress, **kwargs)

def squeezenet1_1(pretrained=False, progress=True, **kwargs):
    return _squeezenet('1_1', pretrained, progress, **kwargs)

2.一些用法

2.1 torch.cat

torch.cat([
            self.expand1x1_activation(self.expand1x1(x)),
            self.expand3x3_activation(self.expand3x3(x))
        ], 1)
#按照第一个维度(channel维度)对[]内的Tensor进行拼接

2.2 nn.MaxPool2d()

nn.MaxPool2d(kernel_size=3, stride=2, ceil_mode=True)
class torch.nn.MaxPool2d(kernel_size, stride=None, padding=0, dilation=1,
                         return_indices=False, ceil_mode=False)
# kernel_size(int or tuple) - max pooling的窗口大小
#stride(int or tuple, optional) - max pooling的窗口移动的步长。默认值是kernel_size
#padding(int or tuple, optional) - 输入的每一条边补充0的层数
#dilation(int or tuple, optional) – 一个控制窗口中元素步幅的参数
#return_indices - 如果等于True,会返回输出最大值的序号,对于上采样操作会有帮助
#ceil_mode - 如果等于True,计算输出信号大小的时候,会使用向上取整,代替默认的向下取整的操作

2.3 使用全卷积代替全连接层

#使用全卷积代替FC层
self.classifier = nn.Sequential(
    nn.Dropout(0.5),
    final_conv,
    nn.ReLU(inplace=True),
    nn.AdaptiveAvgPool2d((1,1))
    )
def forward(self, x):
    x = self.features(x)
    x = self.classifier(x)
    return x.view(x.size(0), self.num_classes)
#即先采用AdaptiveAvgPool2D,将size变为1x1,channel数=num_classes,再做resize
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)

Pytorch源码学习之四:torchvision.models.squeezenet 的相关文章

  • 下载变压器模型以供离线使用

    我有一个训练有素的 Transformer NER 模型 我想在未连接到互联网的机器上使用它 加载此类模型时 当前会将缓存文件下载到 cache 文件夹 要离线加载并运行模型 需要将 cache 文件夹中的文件复制到离线机器上 然而 这些文
  • pytorch 中的 keras.layers.Masking 相当于什么?

    我有时间序列序列 我需要通过将零填充到矩阵中并在 keras 中使用 keras layers Masking 来将序列的长度固定为一个数字 我可以忽略这些填充的零以进行进一步的计算 我想知道它怎么可能在 Pytorch 中完成 要么我需要
  • Pytorch Tensor 如何获取元素索引? [复制]

    这个问题在这里已经有答案了 我有 2 个名为x and list它们的定义如下 x torch tensor 3 list torch tensor 1 2 3 4 5 现在我想获取元素的索引x from list 预期输出是一个整数 2
  • 如何使用Python计算多类分割任务的dice系数?

    我想知道如何计算多类分割的骰子系数 这是计算二元分割任务的骰子系数的脚本 如何循环每个类并计算每个类的骰子 先感谢您 import numpy def dice coeff im1 im2 empty score 1 0 im1 numpy
  • Django:什么时候运行 makemigrations?

    除了向模型添加 删除 修改字段之外 当我向模型添加或修改方法时 Django 还会检测到更改 所以我的问题是我应该跑步吗makemigrations每次我在模型中更改或添加新方法时 当您添加 更改模型方法时 您不需要运行 manage ma
  • 在 Pytorch 中估计高斯模型的混合

    我实际上想估计一个以高斯混合作为基本分布的归一化流 所以我有点被火炬困住了 但是 您可以通过估计 torch 中高斯模型的混合来在代码中重现我的错误 我的代码如下 import numpy as np import matplotlib p
  • 如何设置管理员批准模型的编辑

    我需要一个普通用户可以编辑模型的系统 但编辑实际上只有在管理员批准后才会发生 我发现了一颗宝石 叫做纸迹 https github com airblade paper trail它确实有模型版本控制 但不具体支持我想要做的事情 我想知道其
  • 如何计算cifar10数据的平均值和标准差

    Pytorch 使用以下值作为 cifar10 数据的平均值和标准差 变换 Normalize 0 5 0 5 0 5 0 5 0 5 0 5 我需要理解计算背后的概念 因为这些数据是 3 通道图像 我不明白什么是相加的 什么是除什么的等等
  • 将 Pytorch LSTM 的状态参数转换为 Keras LSTM

    我试图将现有的经过训练的 PyTorch 模型移植到 Keras 中 在移植过程中 我陷入了LSTM层 LSTM 网络的 Keras 实现似乎具有三种状态类型的状态矩阵 而 Pytorch 实现则具有四种状态矩阵 例如 对于hidden l
  • ValueError:使用火炬张量时需要解压的值太多

    对于神经网络项目 我使用 Pytorch 并使用 EMNIST 数据集 已经给出的代码加载到数据集中 train dataset dsets MNIST root data train True transform transforms T
  • 对 FastAI 中的数据应用图像增强转换时出错

    我正在尝试复制这个 Kaggle 笔记本https www kaggle com tanlikesmath diabetic retinopathy with resnet50 oversampling https www kaggle c
  • PyTorch LSTM 中的“隐藏”和“输出”有什么区别?

    我无法理解 PyTorch 的 LSTM 模块 以及类似的 RNN 和 GRU 的文档 关于输出 它说 输出 输出 h n c n 输出 seq len batch hidden size num directions 包含RNN最后一层的
  • 如何同时有效地运行多个 Pytorch 进程/模型? Traceback:分页文件太小,无法完成此操作

    背景 我有一个非常小的网络 我想用不同的随机种子进行测试 该网络几乎只使用了我的 GPU 计算能力的 1 因此理论上我可以同时运行 50 个进程来同时尝试许多不同的种子 Problem 不幸的是我什至无法在多个进程中导入 pytorch 当
  • Huggingface 变形金刚模块未被 anaconda 识别

    我正在使用 Anaconda python 3 7 Windows 10 我尝试通过安装变压器https huggingface co transformers https huggingface co transformers 在我的环境
  • softmax_cross_entropy_with_logits 的 PyTorch 等效项

    我想知道 TensorFlow 是否有等效的 PyTorch 损失函数softmax cross entropy with logits TensorFlow 是否有等效的 PyTorch 损失函数softmax cross entropy
  • Pytorch RuntimeError:张量 a (4) 的大小必须与非单维 0 处张量 b (3) 的大小匹配

    我使用的代码来自here https www learnopencv com image classification using transfer learning in pytorch 训练模型来预测印刷样式编号0 to 9 idx t
  • PyInstaller 可执行文件无法获取 TorchScript 源代码

    我正在尝试使包含 PyTorch 的脚本在 Windows 中可执行 我的脚本的导入是 import numpy core multiarray which is a workaround for ImportError numpy cor
  • PyTorch 中的数据增强

    我对 PyTorch 中执行的数据增强有点困惑 现在 据我所知 当我们执行数据增强时 我们保留原始数据集 然后添加它的其他版本 翻转 裁剪 等 但 PyTorch 中似乎并没有发生这种情况 据我从参考文献中了解到 当我们使用data tra
  • PyTorch 中的标签平滑

    我正在建造一个ResNet 18分类模型为斯坦福汽车使用迁移学习的数据集 我想实施标签平滑 https arxiv org pdf 1701 06548 pdf惩罚过度自信的预测并提高泛化能力 TensorFlow有一个简单的关键字参数Cr
  • 将 Pytorch 模型 .pth 转换为 onnx 模型

    我有一个预训练的模型 其格式为 pth 扩展名 我想将其转换为 Tensorflow protobuf 但我没有找到任何方法来做到这一点 我见过 onnx 可以将模型从 pytorch 转换为 onnx 然后从 onnx 转换为 Tenso

随机推荐