GhostNet(CVPR 2020)学习笔记 (附代码)

news2025/7/22 5:35:14

 论文地址:​​​​​​https://arxiv.org/abs/1911.11907v2

代码地址:https://github.com/huawei-noah/Efficient-AI-Backbones/blob/master/ghostnet_pytorch/ghostnet.py

1.是什么?

Ghost module是一种模型压缩的方法,它可以在保证网络精度的同时减少网络参数和计算量,从而提升计算速度和降低延时。Ghost模块可以代替现有卷积网络中的每一个卷积层。Ghost module的核心思想是将一个卷积层分解成两个较小的卷积层,其中一个卷积层被称为ghost卷积层,它只使用原始卷积层的一小部分通道来计算输出,而另一个卷积层则被称为剩余卷积层,它使用剩余的通道来计算输出。这种分解方式可以大大减少计算量和参数数量,同时保持网络的精度。Ghost module已经被应用于GhostNet等网络架构中,并取得了出色的表现。

2.为什么?


由于硬件资源以及计算量的限制,在嵌入式设备当中部署卷积神经网络是很困难的。想要解决这个问题,就要想方设法的使网络模型更加的轻量化。现存的网络模型轻量化方法一般有两种:模型压缩和轻量化网络设计。

模型压缩:

pruning connection: 减去一些不重要的神经元连接;
channel pruning: 通道剪枝,减去一些无用的通道,以便加速运算;
model quantization: 模型量化,在具有离散值的神经网络中对权重或激活函数进行压缩和计算加速;
tensor decomposition: 张量分解,通过权重的冗余性和low-link来减少参数或计算;
knowledge distillation: 知识蒸馏, 利用大模型来教小模型,提高小模型的性能
轻量化网络设计:

Xception: depthwise conv operation
MobileNet 系列: 深度可分离卷积 depthwise separable conv、inverted resdual block、AutoML technology
ShuffleNet 系列: channel shuffle operation
尽管这些模型获得了良好的性能,但是feature map之间的相关性和冗余性一直没有得到很好的利用。

那么什么是feature map之间的相关性和冗余性呢?

作者在实验过程中将ResNet50的第一个残差组的feature map进行可视化,发现里面有三对feature map(如下图中的红绿蓝三对feature map)它们极其相似,作者认为这些feature map对之间是冗余的(相关的)。

每张图代表一个通道,图中三组颜色相连的图非常相似。论文将一组中的一张图称为本征图(intrinsic),其他和本征图相似的图称为本征图的魅影(ghost)。那么,既然ghost和Intrinsic非常相似,我们是否可以通过一种相对简单的、计算量较少的运算代替运算量大的卷积操作生成ghost图?ghost模块就是基于这种想法,提出用简单的线性运算生成ghost,但总共的通道数(# intrinsic+ghost)以及生成特征图的大小和原来保持一致。

作者考虑到这些feature map层中的冗余信息可能是一个成功模型的重要组成部分,正是因为这些冗余信息才能保证输入数据的全面理解,所以作者在设计轻量化模型的时候并没有试图去除这些冗余feature map,而是尝试使用更低成本的计算量来获取这些冗余feature map。

作者生动的将这些冗余的feature map称为 Ghost(幽灵) 。
 

3.怎么样?

3.1 Ghost Module

生成ghost图的过程采用简单的线性运算Φ,代替原本的卷积操作。如下图所示,假设原始卷积操作中输入Input与n组k x k的Kernel卷积后生成通道数为n,尺寸为h’ x w’大小的输出。在ghost模型中,我们用m组k x k的Kernel与input进行卷积,生成m x h’ x w’的本征图intrinsic,之后本征图进行线性变换Φ产生ghost图,将intrinsic和ghost一起作为输出。

3.2 模型压缩量定量计算

下面计算用一个ghost模块取代原始的一层卷积操作带来多少计算量、参数量上的优势。

加速比(rs:speed up ratio):这里用计算量来近似代替速度。

压缩比(compression ratio):

3.3 GhostNet

网络参数

3.4 代码实现

GhostModule

class GhostModule(nn.Module):
    def __init__(self, inp, oup, kernel_size=1, ratio=2, dw_size=3, stride=1, relu=True):
        super(GhostModule, self).__init__()
        self.oup = oup
        init_channels = math.ceil(oup / ratio)
        new_channels = init_channels*(ratio-1)

        self.primary_conv = nn.Sequential(
            nn.Conv2d(inp, init_channels, kernel_size, stride, kernel_size//2, bias=False),
            nn.BatchNorm2d(init_channels),
            nn.ReLU(inplace=True) if relu else nn.Sequential(),
        )

        self.cheap_operation = nn.Sequential(
            nn.Conv2d(init_channels, new_channels, dw_size, 1, dw_size//2, groups=init_channels, bias=False),
            nn.BatchNorm2d(new_channels),
            nn.ReLU(inplace=True) if relu else nn.Sequential(),
        )

    def forward(self, x):
        x1 = self.primary_conv(x)
        x2 = self.cheap_operation(x1)
        out = torch.cat([x1,x2], dim=1)
        return out[:,:self.oup,:,:]

GhostNet

# 2020.06.09-Changed for building GhostNet
#            Huawei Technologies Co., Ltd. <foss@huawei.com>
"""
Creates a GhostNet Model as defined in:
GhostNet: More Features from Cheap Operations By Kai Han, Yunhe Wang, Qi Tian, Jianyuan Guo, Chunjing Xu, Chang Xu.
https://arxiv.org/abs/1911.11907
Modified from https://github.com/d-li14/mobilenetv3.pytorch and https://github.com/rwightman/pytorch-image-models
"""
import torch
import torch.nn as nn
import torch.nn.functional as F
import math


__all__ = ['ghost_net']


def _make_divisible(v, divisor, min_value=None):
    """
    This function is taken from the original tf repo.
    It ensures that all layers have a channel number that is divisible by 8
    It can be seen here:
    https://github.com/tensorflow/models/blob/master/research/slim/nets/mobilenet/mobilenet.py
    """
    if min_value is None:
        min_value = divisor
    new_v = max(min_value, int(v + divisor / 2) // divisor * divisor)
    # Make sure that round down does not go down by more than 10%.
    if new_v < 0.9 * v:
        new_v += divisor
    return new_v


def hard_sigmoid(x, inplace: bool = False):
    if inplace:
        return x.add_(3.).clamp_(0., 6.).div_(6.)
    else:
        return F.relu6(x + 3.) / 6.


class SqueezeExcite(nn.Module):
    def __init__(self, in_chs, se_ratio=0.25, reduced_base_chs=None,
                 act_layer=nn.ReLU, gate_fn=hard_sigmoid, divisor=4, **_):
        super(SqueezeExcite, self).__init__()
        self.gate_fn = gate_fn
        reduced_chs = _make_divisible((reduced_base_chs or in_chs) * se_ratio, divisor)
        self.avg_pool = nn.AdaptiveAvgPool2d(1)
        self.conv_reduce = nn.Conv2d(in_chs, reduced_chs, 1, bias=True)
        self.act1 = act_layer(inplace=True)
        self.conv_expand = nn.Conv2d(reduced_chs, in_chs, 1, bias=True)

    def forward(self, x):
        x_se = self.avg_pool(x)
        x_se = self.conv_reduce(x_se)
        x_se = self.act1(x_se)
        x_se = self.conv_expand(x_se)
        x = x * self.gate_fn(x_se)
        return x    

    
class ConvBnAct(nn.Module):
    def __init__(self, in_chs, out_chs, kernel_size,
                 stride=1, act_layer=nn.ReLU):
        super(ConvBnAct, self).__init__()
        self.conv = nn.Conv2d(in_chs, out_chs, kernel_size, stride, kernel_size//2, bias=False)
        self.bn1 = nn.BatchNorm2d(out_chs)
        self.act1 = act_layer(inplace=True)

    def forward(self, x):
        x = self.conv(x)
        x = self.bn1(x)
        x = self.act1(x)
        return x


class GhostModule(nn.Module):
    def __init__(self, inp, oup, kernel_size=1, ratio=2, dw_size=3, stride=1, relu=True):
        super(GhostModule, self).__init__()
        self.oup = oup
        init_channels = math.ceil(oup / ratio)
        new_channels = init_channels*(ratio-1)

        self.primary_conv = nn.Sequential(
            nn.Conv2d(inp, init_channels, kernel_size, stride, kernel_size//2, bias=False),
            nn.BatchNorm2d(init_channels),
            nn.ReLU(inplace=True) if relu else nn.Sequential(),
        )

        self.cheap_operation = nn.Sequential(
            nn.Conv2d(init_channels, new_channels, dw_size, 1, dw_size//2, groups=init_channels, bias=False),
            nn.BatchNorm2d(new_channels),
            nn.ReLU(inplace=True) if relu else nn.Sequential(),
        )

    def forward(self, x):
        x1 = self.primary_conv(x)
        x2 = self.cheap_operation(x1)
        out = torch.cat([x1,x2], dim=1)
        return out[:,:self.oup,:,:]


class GhostBottleneck(nn.Module):
    """ Ghost bottleneck w/ optional SE"""

    def __init__(self, in_chs, mid_chs, out_chs, dw_kernel_size=3,
                 stride=1, act_layer=nn.ReLU, se_ratio=0.):
        super(GhostBottleneck, self).__init__()
        has_se = se_ratio is not None and se_ratio > 0.
        self.stride = stride

        # Point-wise expansion
        self.ghost1 = GhostModule(in_chs, mid_chs, relu=True)

        # Depth-wise convolution
        if self.stride > 1:
            self.conv_dw = nn.Conv2d(mid_chs, mid_chs, dw_kernel_size, stride=stride,
                             padding=(dw_kernel_size-1)//2,
                             groups=mid_chs, bias=False)
            self.bn_dw = nn.BatchNorm2d(mid_chs)

        # Squeeze-and-excitation
        if has_se:
            self.se = SqueezeExcite(mid_chs, se_ratio=se_ratio)
        else:
            self.se = None

        # Point-wise linear projection
        self.ghost2 = GhostModule(mid_chs, out_chs, relu=False)
        
        # shortcut
        if (in_chs == out_chs and self.stride == 1):
            self.shortcut = nn.Sequential()
        else:
            self.shortcut = nn.Sequential(
                nn.Conv2d(in_chs, in_chs, dw_kernel_size, stride=stride,
                       padding=(dw_kernel_size-1)//2, groups=in_chs, bias=False),
                nn.BatchNorm2d(in_chs),
                nn.Conv2d(in_chs, out_chs, 1, stride=1, padding=0, bias=False),
                nn.BatchNorm2d(out_chs),
            )


    def forward(self, x):
        residual = x

        # 1st ghost bottleneck
        x = self.ghost1(x)

        # Depth-wise convolution
        if self.stride > 1:
            x = self.conv_dw(x)
            x = self.bn_dw(x)

        # Squeeze-and-excitation
        if self.se is not None:
            x = self.se(x)

        # 2nd ghost bottleneck
        x = self.ghost2(x)
        
        x += self.shortcut(residual)
        return x


class GhostNet(nn.Module):
    def __init__(self, cfgs, num_classes=1000, width=1.0, dropout=0.2):
        super(GhostNet, self).__init__()
        # setting of inverted residual blocks
        self.cfgs = cfgs
        self.dropout = dropout

        # building first layer
        output_channel = _make_divisible(16 * width, 4)
        self.conv_stem = nn.Conv2d(3, output_channel, 3, 2, 1, bias=False)
        self.bn1 = nn.BatchNorm2d(output_channel)
        self.act1 = nn.ReLU(inplace=True)
        input_channel = output_channel

        # building inverted residual blocks
        stages = []
        block = GhostBottleneck
        for cfg in self.cfgs:
            layers = []
            for k, exp_size, c, se_ratio, s in cfg:
                output_channel = _make_divisible(c * width, 4)
                hidden_channel = _make_divisible(exp_size * width, 4)
                layers.append(block(input_channel, hidden_channel, output_channel, k, s,
                              se_ratio=se_ratio))
                input_channel = output_channel
            stages.append(nn.Sequential(*layers))

        output_channel = _make_divisible(exp_size * width, 4)
        stages.append(nn.Sequential(ConvBnAct(input_channel, output_channel, 1)))
        input_channel = output_channel
        
        self.blocks = nn.Sequential(*stages)        

        # building last several layers
        output_channel = 1280
        self.global_pool = nn.AdaptiveAvgPool2d((1, 1))
        self.conv_head = nn.Conv2d(input_channel, output_channel, 1, 1, 0, bias=True)
        self.act2 = nn.ReLU(inplace=True)
        self.classifier = nn.Linear(output_channel, num_classes)

    def forward(self, x):
        x = self.conv_stem(x)
        x = self.bn1(x)
        x = self.act1(x)
        x = self.blocks(x)
        x = self.global_pool(x)
        x = self.conv_head(x)
        x = self.act2(x)
        x = x.view(x.size(0), -1)
        if self.dropout > 0.:
            x = F.dropout(x, p=self.dropout, training=self.training)
        x = self.classifier(x)
        return x


def ghostnet(**kwargs):
    """
    Constructs a GhostNet model
    """
    cfgs = [
        # k, t, c, SE, s 
        # stage1
        [[3,  16,  16, 0, 1]],
        # stage2
        [[3,  48,  24, 0, 2]],
        [[3,  72,  24, 0, 1]],
        # stage3
        [[5,  72,  40, 0.25, 2]],
        [[5, 120,  40, 0.25, 1]],
        # stage4
        [[3, 240,  80, 0, 2]],
        [[3, 200,  80, 0, 1],
         [3, 184,  80, 0, 1],
         [3, 184,  80, 0, 1],
         [3, 480, 112, 0.25, 1],
         [3, 672, 112, 0.25, 1]
        ],
        # stage5
        [[5, 672, 160, 0.25, 2]],
        [[5, 960, 160, 0, 1],
         [5, 960, 160, 0.25, 1],
         [5, 960, 160, 0, 1],
         [5, 960, 160, 0.25, 1]
        ]
    ]
    return GhostNet(cfgs, **kwargs)


if __name__=='__main__':
    model = ghostnet()
    model.eval()
    print(model)
    input = torch.randn(32,3,320,256)
    y = model(input)
    print(y.size())

原文链接:https://blog.csdn.net/qq_38253797/article/details/118487753

 

参考:

GhostNet(CVPR 2020) 原理与代码解析

本文来自互联网用户投稿,该文观点仅代表作者本人,不代表本站立场。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如若转载,请注明出处:http://www.coloradmin.cn/o/1157135.html

如若内容造成侵权/违法违规/事实不符,请联系多彩编程网进行投诉反馈,一经查实,立即删除!

相关文章

韦东山D1S板子——利用xfel工具初始化内置64MB内存,并直接下载程序到内存运行

1、前言 &#xff08;1&#xff09;最近使用韦东山老师的D1S板子学习RISC-V架构知识&#xff0c;我是结合《RISC-V体系结构编程与实践》这本书的进行学习&#xff0c;其中韦东山老师对书中的代码做了部分移植&#xff0c;到MMU模块就没有在移植书中代码&#xff1b; &#xff0…

从小白到大牛:Linux嵌入式系统开发的完整指南

Linux嵌入式系统开发一直是一个激动人心的领域&#xff0c;吸引着越来越多的开发者。无论你是初学者还是已经有一些经验的开发者&#xff0c;本文将为你提供从小白到大牛的完整指南&#xff0c;帮助你掌握Linux嵌入式系统开发的关键概念和技能。我们将深入探讨Linux内核、设备驱…

从开发者的角度看K8S中的复合容器模式

就应用设计最佳实践和原则而言&#xff0c;构建复杂的基于容器的架构与编程没有太大区别。本文的目标是使用众所周知的编程原理从开发人员的角度展示三种流行的可扩展性架构模式。 让我们从单一职责原则开始。根据 R. Martin 的说法&#xff0c;“一个类应该只有一个改变的理由…

高性能渲染——详解Html Canvas的优势与性能

本文由葡萄城技术团队原创并首发。转载请注明出处&#xff1a;葡萄城官网&#xff0c;葡萄城为开发者提供专业的开发工具、解决方案和服务&#xff0c;赋能开发者。 一、什么是Canvas 想必学习前端的同学们对Canvas 都不陌生&#xff0c;它是 HTML5 新增的“画布”元素&#x…

污水一体处理设备工艺有哪些

污水一体处理设备工艺主要包括以下几种&#xff1a; AO工艺&#xff1a;AO工艺是增加好氧池缺氧池形成硝化-反硝化系统&#xff0c;处理污水中氮含量效率提升。SBR工艺&#xff1a;SBR工艺是按间歇曝气方式运行的活性污泥处理技术&#xff0c;厌氧、好氧、缺氧处于交替状态&am…

选择适合制造业的企业邮箱平台

自2010年成立以来&#xff0c;J公司已从一家小型有限责任公司发展成为全球领先的工业内窥镜研发、生产和销售企业。公司的产品制造采用国际先进技术和一流生产工艺&#xff0c;专业为客户提供定制解决方案&#xff0c;产品已广泛应用于锅检特检、机械制造、发电、石油、燃气、化…

AWS认证考试的那些事

1 为啥会有这个认证 你既然点进来了这个也就不重要了&#xff0c;重要的是怎么拿到他&#xff0c;以SAA-C03为例&#xff0c;从开始到结束我们一起来进行准备 2 考试卷 目前AWS的考试是要交钱的&#xff0c;正常情况下拿到5折劵很容易&#xff0c;比如你之前考过AWS的认证会给…

蓝牙 - LE的Connection Parameters设定

BLE链接参数设定 两个BLE设备建立链接后&#xff0c;可以更改链接参数。Central和Peripheral设备均可发送更新链接参数请求。这个在很多时候是有必要的&#xff0c;因为广播扫描的建立链接过程&#xff0c;和链接保持的过程&#xff0c;对链接参数的要求是不同的。比如设置连接…

LInux之在同一Tomcat下使用不同的端口号访问不同的项目

&#x1f389;&#x1f389;欢迎来到我的CSDN主页&#xff01;&#x1f389;&#x1f389; &#x1f3c5;我是君易--鑨&#xff0c;一个在CSDN分享笔记的博主。&#x1f4da;&#x1f4da; &#x1f31f;推荐给大家我的博客专栏《LInux实战开发》。&#x1f3af;&#x1f3af; …

深入探索 C++ 多态 ② - 继承关系

前言 上一章 简述了虚函数的调用链路&#xff0c;本章主要探索 C 各种继承关系的类对象的多态特性。 深入探索 C 多态 ① - 虚函数调用链路深入探索 C 多态 ② - 继承关系深入探索 C 多态 ③ - 虚析构 1. 概述 封装&#xff0c;继承&#xff0c;多态是 C 的三大特性&#xf…

群晖 Docker版qbittorrent 下载显示错误 解决方法

这些天在折腾AIO玩&#xff0c;PVE虚拟机底层&#xff0c;核显直通&#xff0c;群晖安装&#xff0c;免不了踩些坑。 今天写篇博客&#xff0c;讲述一下群晖 Docker版qbittorrent 下载显示错误的解决方法&#xff0c;顺便记录一下配置&#xff0c;以便日后折腾可以参考。 直接…

4.讲究先来后到的队列

概述 目标&#xff1a; 队列的存储结构及操作特点java中队列相关的api基于单链表的队列实现刷题(设计循环队列) 存储结构及特点 队列(queue) 和栈一样&#xff0c;代表具有一类操作特征的数据结构&#xff0c;拿日常生活中的一个场景举例说明&#xff0c;去车站的窗口买票&…

百度上传自己个人简介攻略,个人介绍百度百科怎么做?

个人介绍要展示在百度百科上该怎么操作&#xff0c;我们都清楚百度百科词条是需要申请才能拥有的&#xff0c;但是没有百度上传自己个人简介的攻略&#xff0c;很多人是不知从何下手的。下面洛希爱做百科网带着大家一起来了解。 一、了解百度百科词条的创建规则 1. 词条名称规…

python项目部署代码汇总:目标检测类、人体姿态类

一、AI健身计数 1、图片视频检测 &#xff08;cpu运行&#xff09;&#xff1a; 注&#xff1a;左上角为fps&#xff0c;左下角为次数统计。 1.哑铃弯举&#xff1a;12&#xff0c;14&#xff0c;16 详细环境安装教程&#xff1a;pyqt5AI健身CPU实时检测mediapipe 可视化界面…

光学雨量计:更灵敏可靠、更智能的降雨监测工具

光学雨量计&#xff1a;更灵敏可靠、更智能的降雨监测工具 降雨量信息是评估大气环境和降水研究的关键指标&#xff0c;也是环境监测和农业安全监测的重要参数。目前&#xff0c;我们通常使用翻斗式或光学雨量计来监测降雨量&#xff0c;这些工具能够感知自然界的降雨量&#…

媒体宣传如何助力品牌发展

传媒如春雨&#xff0c;润物细无声&#xff0c;大家好&#xff0c;我是51媒体网胡老师。 媒体宣传可以在多方面助力品牌发展&#xff0c;下面是一些关键的方式&#xff1a; 1. 提高品牌知名度&#xff1a;媒体宣传可以将品牌曝光给更广泛的受众&#xff0c;使更多人了解您的品…

内涝积水监测仪怎么样?万宾科技城市内涝积水监测的作用

在城市建设发展过程中&#xff0c;道路基础设施的建设永远都占据着重要一席&#xff0c;因为人们出行一旦受阻便会影响城市进展&#xff0c;也会影响经济发展。在城市之中有隧道&#xff0c;下穿式立交桥等容易存积水的地方&#xff0c;一旦出现恶劣暴雨天气&#xff0c;这些地…

CHAT——新手必看的文章

今天小编用CHAT写一篇文章&#xff1a;Ipad新手注意事项&#xff0c;一定要看。 标题&#xff1a;iPad新手必读&#xff1a;一篇你绝对不能错过的关于iPad使用的注意事项 当你买了一台全新的iPad&#xff0c;无论是为了工作还是娱乐&#xff0c;这款强大而引人入胜的设备都提供…

Wonder3D:用单张图片生成纹理网格

Wonder3D 只需 2 ∼ 3 分钟即可从单视图图像重建高度详细的纹理网格。 Wonder3D首先通过跨域扩散模型生成一致的多视图法线图和相应的彩色图像&#xff0c;然后利用新颖的法线融合方法实现快速、高质量的重建。 推荐&#xff1a;用 NSDT编辑器 快速搭建可编程3D场景 1、推理准…

Linux ---------------------Shell 基本运算符

&#xff08;一&#xff09;摘要 Shell 和其他编程语言一样&#xff0c;支持多种运算符&#xff0c;包括&#xff1a; 算数运算符关系运算符布尔运算符字符串运算符文件测试运算符 原生bash不支持简单的数学运算&#xff0c;但是可以通过其他命令来实现&#xff0c;例如 awk …