【YOLOV5-5.x 源码解读】activations.py

前言

源码: YOLOv5源码.
链接: 【YOLOV5-5.x 源码讲解】整体项目文件导航.
注释版全部项目文件已上传至GitHub: yolov5-5.x-annotations.

这个文件是yolov5做的一些关于激活函数改进的实验,且都是近年来比较火的也是效果比较好的一些激活函数。大家可以尽情的尝试放在自己的数据集或者模型上试试效果。

使用起来也很方便,直接修改common.py在的Conv函数即可:

class Conv(nn.Module):  # Standard convolution
    def __init__(self, c1, c2, k=1, s=1, p=None, g=1, act=True):  # ch_in, ch_out, kernel, stride, padding, groups
        """
        Standard convolution  conv+BN+act
        :params c1: 输入的channel值
        :params c2: 输出的channel值
        :params k: 卷积的kernel_size
        :params s: 卷积的stride
        :params p: 卷积的padding  一般是None  可以通过autopad自行计算需要pad的padding数
        :params g: 卷积的groups数  =1就是普通的卷积  >1就是深度可分离卷积
        :params act: 激活函数类型   True就是SiLU()/Swish   False就是不使用激活函数
                     类型是nn.Module就使用传进来的激活函数类型
        """
        super(Conv, self).__init__()
        self.conv = nn.Conv2d(c1, c2, k, s, autopad(k, p), groups=g, bias=False)
        self.bn = nn.BatchNorm2d(c2)
        # self.act = nn.Identity() if act is True else (act if isinstance(act, nn.Module) else nn.Identity())
        # self.act = nn.Tanh() if act is True else (act if isinstance(act, nn.Module) else nn.Identity())
        # self.act = nn.Sigmoid() if act is True else (act if isinstance(act, nn.Module) else nn.Identity())
        # self.act = nn.ReLU() if act is True else (act if isinstance(act, nn.Module) else nn.Identity())
        # self.act = nn.LeakyReLU(0.1) if act is True else (act if isinstance(act, nn.Module) else nn.Identity())
        # self.act = nn.Hardswish() if act is True else (act if isinstance(act, nn.Module) else nn.Identity())
        self.act = nn.SiLU() if act is True else (act if isinstance(act, nn.Module) else nn.Identity())
        # self.act = Mish() if act is True else (act if isinstance(act, nn.Module) else nn.Identity())
        # self.act = FReLU(c2) if act is True else (act if isinstance(act, nn.Module) else nn.Identity())
        # self.act = AconC(c2) if act is True else (act if isinstance(act, nn.Module) else nn.Identity())
        # self.act = MetaAconC(c2) if act is True else (act if isinstance(act, nn.Module) else nn.Identity())
        # self.act = DyReLUA(c2, conv_type='2d') if act is True else (act if isinstance(act, nn.Module) else nn.Identity())
        # self.act = DyReLUB(c2, conv_type='2d') if act is True else (act if isinstance(act, nn.Module) else nn.Identity())

    def forward(self, x):
        return self.act(self.bn(self.conv(x)))

    def fuseforward(self, x):
        """
        前向融合conv+bn计算  减少推理时间
        """
        return self.act(self.conv(x))

导包部分:

# Activation functions

import torch
import torch.nn as nn
import torch.nn.functional as F

0、ReLU、Leaky ReLU、PReLU、RReLU

在这里插入图片描述

ReLU优点:

  1. 不会发生梯度消失问题。Sigmoid函数在 x>0 会发生梯度消失问题,造成信息损失,从而无法完成深度网络的训练。而 ReLU 函数当 x>0 为线性结构,有固定的梯度,不会消失。
  2. ReLU激活函数在 x<0 时会输出为0(失活),这可以造成网络的稀疏性。这样可以很好的模拟人脑神经元工作的原理,且可以减少参数间的相互依赖,缓解了过拟合问题的发生。
  3. Sigmoid/tanh 函数复杂,计算量大(前向传播+反向传播求导),速度慢;而ReLU函数简单,计算量小,速度快。

ReLU缺点:

  1. (重要)ReLU在训练的时候很”脆弱”,很可能产生 Dead ReLU Problem(神经元坏死现象):某些神经元可能永远不会被激活,导致相应参数永远不会被更新(在负数部分,梯度为0)。举个例子:由于ReLU在x<0时梯度为0,这样就导致负的梯度在这个ReLU被置零,而且这个神经元有可能再也不会被任何数据激活。如果这个情况发生了,那么这个神经元之后的梯度就永远是0了,也就是ReLU神经元坏死了,不再对任何数据有所响应。

正是为了解决上面的 Dead ReLU Problem(神经元坏死现象),先后提出了Leaky ReLU、PReLU、RReLU三种方法,在 x<0 部分不武断的赋为0,而是给它一个很小的斜率,这样可以有效的缓解/解决这个问题。Leaky ReLU及其变体(PReLU、RReLU)的性能都要优于ReLU激活函数;而RReLU由于具有良好的训练随机性,可以很好的防止过拟合。

这几个函数的代码上直接像上面那样调用torch包就可以实现,这里就不多说了。

更多关于ReLU激活函数的知识可以看我的另一篇博文:【论文复现】ReLU Activation(2011).

更多关于ReLU及其家族激活函数的区别联系可以看我的另一篇博文:【论文复现】ReLU、Leaky ReLU、PReLU、RReLU实验对比(2015).

1、Swish/SiLU

在这里插入图片描述
在这里插入图片描述

Swish是使用自动搜索技术自动的搜索最佳的激活函数(多个一元或者二元函数组合)。暴力搜索出来的,并没有解释为什么好。

Swis优点:

  1. 无上界(避免过拟合)
  2. 有下界(产生更强的正则化效果)
  3. 平滑(处处可导 更容易训练)
  4. x<0具有非单调性(对分布有重要意义 这点也是Swish和ReLU的最大区别)。

更多关于Swish激活函数的知识可以看我的另一篇博文:【论文复现】Swish-Activation(2017).

代码
下面这个函数是Swish实现的普通版本:

class SiLU(nn.Module):
    # SiLU/Swish
    # https://arxiv.org/pdf/1606.08415.pdf
    @staticmethod
    def forward(x):
        return x * torch.sigmoid(x)  # 默认参数 = 1

下面这个函数实现的是Swish函数的高效版本(自己写前向传播和反向传播):

class MemoryEfficientSwish(nn.Module):
    # 节省内存的Swish 不采用自动求导(自己写前向传播和反向传播) 更高效
    class F(torch.autograd.Function):
        @staticmethod
        def forward(ctx, x):
            # save_for_backward会保留x的全部信息(一个完整的外挂Autograd Function的Variable),
            # 并提供避免in-place操作导致的input在backward被修改的情况.
            # in-place操作指不通过中间变量计算的变量间的操作。
            ctx.save_for_backward(x)
            return x * torch.sigmoid(x)

        @staticmethod
        def backward(ctx, grad_output):
            # 此处saved_tensors[0] 作用同上文 save_for_backward
            x = ctx.saved_tensors[0]
            sx = torch.sigmoid(x)
            # 返回该激活函数求导之后的结果 求导过程见上文
            return grad_output * (sx * (1 + x * (1 - sx)))

    def forward(self, x): # 应用前向传播方法
        return self.F.apply(x)

另外这个函数实现的是一个和Swish函数很形似的一个激活函数:

class Hardswish(nn.Module):
    """
    hard-swish 图形和Swish很相似 在mobilenet v3中提出
    https://arxiv.org/pdf/1905.02244.pdf
    """
    @staticmethod
    def forward(x):
        # return x * F.hardsigmoid(x)  # for torchscript and CoreML
        return x * F.hardtanh(x + 3, 0., 6.) / 6.  # for torchscript, CoreML and ONNX

2、Mish

一种新型的自正则化的非单调激活函数
在这里插入图片描述
在这里插入图片描述
Mish特点:

  1. 无上界,非饱和,避免了因饱和而导致梯度为0(梯度消失/梯度爆炸),进而导致训练速度大大下降;
  2. 有下界,在负半轴有较小的权重,可以防止ReLU函数出现的神经元坏死现象;同时可以产生更强的正则化效果;
  3. 自身本就具有自正则化效果(公式可以推导),可以使梯度和函数本身更加平滑(Smooth),且是每个点几乎都是平滑的,这就更容易优化而且也可以更好的泛化。随着网络越深,信息可以更深入的流动。
  4. x<0,保留了少量的负信息,避免了ReLU的Dying ReLU现象,这有利于更好的表达和信息流动。
  5. 连续可微,避免奇异点
  6. 非单调

更多关于Mish激活函数的知识可以看我的另一篇博文:【论文复现】Mish Activation(2020).

代码
下面是Mish激活函数的普通版本:

class Mish(nn.Module):
    """
    Mish 激活函数
    https://arxiv.org/pdf/1908.08681.pdf
    https://github.com/digantamisra98/Mish/blob/master/Mish/Torch/mish.py
    """
    @staticmethod
    def forward(x):
        return x * F.softplus(x).tanh()  # softplus(x) = ln(1 + exp(x)

下面这个函数实现的是Mish函数的高效版本(自己写前向传播和反向传播):

class MemoryEfficientMish(nn.Module):
    """
    一种高效的Mish激活函数  不采用自动求导(自己写前向传播和反向传播) 更高效
    """
    class F(torch.autograd.Function):
        @staticmethod
        def forward(ctx, x):
            # 前向传播
            # save_for_backward函数可以将对象保存起来,用于后续的backward函数
            # 会保留此input的全部信息,并提供避免in_place操作导致的input在backward中被修改的情况
            ctx.save_for_backward(x)
            return x.mul(torch.tanh(F.softplus(x)))  # x * tanh(ln(1 + exp(x)))

        @staticmethod
        def backward(ctx, grad_output):
            # 反向传播
            x = ctx.saved_tensors[0]
            sx = torch.sigmoid(x)
            fx = F.softplus(x).tanh()
            return grad_output * (fx + x * sx * (1 - fx * fx))

    def forward(self, x):
        return self.F.apply(x)

3、FReLU

FReLU(Funnel ReLU 漏斗ReLU)非线性激活函数,在只增加一点点的计算负担的情况下,将ReLU和PReLU扩展成2D激活函数。具体的做法是将max()函数内的条件部分(原先ReLU的x<0部分)换成了2D的漏斗条件(代码是通过DepthWise Separable Conv + BN 实现的),解决了激活函数中的空间不敏感问题,使规则(普通)的卷积也具备捕获复杂的视觉布局能力,使模型具备像素级建模的能力。

在这里插入图片描述
在这里插入图片描述
更多关于FReLU激活函数的知识可以看我的另一篇博文:【论文复现】FReLU Activation(2020).

代码
下面这个函数是根据论文我们实现的FReLU,很简单,就用了一个深度可分离卷积 DepthWise Separable Conv + BN :

class FReLU(nn.Module):
    """
    FReLU https://arxiv.org/abs/2007.11824
    """
    def __init__(self, c1, k=3):  # ch_in, kernel
        super().__init__()
        # 定义漏斗条件T(x)  参数池窗口(Parametric Pooling Window )来创建空间依赖
        # nn.Con2d(in_channels, out_channels, kernel_size, stride, padding, dilation=1, bias=True)
        # 使用 深度可分离卷积 DepthWise Separable Conv + BN 实现T(x)
        self.conv = nn.Conv2d(c1, c1, k, 1, 1, groups=c1, bias=False)
        self.bn = nn.BatchNorm2d(c1)

    def forward(self, x):
        # f(x)=max(x, T(x))
        return torch.max(x, self.bn(self.conv(x)))

4、AconC、meta-AconC

这是2021年新出的一个激活函数,先从ReLU函数出发,采用Smoth maximum近似平滑公式证明了Swish就是ReLU函数的近似平滑表示,这也算提出一种新颖的Swish函数解释(Swish不再是一个黑盒)。之后进一步分析ReLU的一般形式Maxout系列激活函数,再次利用Smoth maximum将Maxout系列扩展得到简单且有效的ACON系列激活函数:ACON-A、ACON-B、ACON-C。最终提出meta-ACON,动态的学习(自适应)激活函数的线性/非线性,显著提高了表现。

在这里插入图片描述

更多关于AconC、meta-AconC激活函数的知识可以看我的另一篇博文:【论文复现】ACON Activation(2021).

代码
下面实现的是Acon论文的第三个版本 AconC:

class AconC(nn.Module):
    """
    ACON https://arxiv.org/pdf/2009.04759.pdf
    ACON activation (activate or not).
    AconC: (p1*x-p2*x) * sigmoid(beta*(p1*x-p2*x)) + p2*x, beta is a learnable parameter
    according to "Activate or Not: Learning Customized Activation" <https://arxiv.org/pdf/2009.04759.pdf>.
    """

    def __init__(self, c1):
        super().__init__()
        self.p1 = nn.Parameter(torch.randn(1, c1, 1, 1))
        self.p2 = nn.Parameter(torch.randn(1, c1, 1, 1))
        self.beta = nn.Parameter(torch.ones(1, c1, 1, 1))

    def forward(self, x):
        dpx = (self.p1 - self.p2) * x
        return dpx * torch.sigmoid(self.beta * dpx) + self.p2 * x

下面实现的是meta-ACON,动态的学习(自适应)激活函数的线性/非线性:

class MetaAconC(nn.Module):
    r""" ACON activation (activate or not).
    MetaAconC: (p1*x-p2*x) * sigmoid(beta*(p1*x-p2*x)) + p2*x, beta is generated by a small network
    according to "Activate or Not: Learning Customized Activation" <https://arxiv.org/pdf/2009.04759.pdf>.
    """

    def __init__(self, c1, k=1, s=1, r=16):  # ch_in, kernel, stride, r
        super().__init__()
        c2 = max(r, c1 // r)
        self.p1 = nn.Parameter(torch.randn(1, c1, 1, 1))
        self.p2 = nn.Parameter(torch.randn(1, c1, 1, 1))
        self.fc1 = nn.Conv2d(c1, c2, k, s, bias=True)
        self.fc2 = nn.Conv2d(c2, c1, k, s, bias=True)
        # self.bn1 = nn.BatchNorm2d(c2)
        # self.bn2 = nn.BatchNorm2d(c1)

    def forward(self, x):
        y = x.mean(dim=2, keepdims=True).mean(dim=3, keepdims=True)
        # batch-size 1 bug/instabilities https://github.com/ultralytics/yolov5/issues/2891
        # beta = torch.sigmoid(self.bn2(self.fc2(self.bn1(self.fc1(y)))))  # bug/unstable
        beta = torch.sigmoid(self.fc2(self.fc1(y)))  # bug patch BN layers removed
        dpx = (self.p1 - self.p2) * x
        return dpx * torch.sigmoid(beta * dpx) + self.p2 * x

5、DyReLU

最后的一个激活函数并不在源码当中,是我自己看的一篇2020的论文,觉得很有趣、很厉害就搬到这里一起总结了。
在这里插入图片描述
在这里插入图片描述
DyReLU特点:

  1. 将所有输入元素 x={ x c x_c xc} 的全局上下文编码在超参数 θ ( x ) \theta(x) θ(x) 中(运用SE模块的注意力机制),以适应激活函数 f θ ( x ) ( x ) f_{\theta(x)}(x) fθ(x)(x)(可以根据输入数据x,动态的学习选择最佳的激活函数)。

更多关于DyReLU激活函数的知识可以看我的另一篇博文:【论文复现】Dynamic ReLU(2020).

代码
下面实现的是DyReLU激活函数的公共函数,用于计算超参数 θ ( x ) \theta(x) θ(x) ,一直计算到上图的Normalization:

class DyReLU(nn.Module):
    def __init__(self, channels, reduction=4, k=2, conv_type='2d'):
        super(DyReLU, self).__init__()
        self.channels = channels
        self.k = k
        self.conv_type = conv_type
        assert self.conv_type in ['1d', '2d']

        self.fc1 = nn.Linear(channels, channels // reduction)
        self.relu = nn.ReLU(inplace=True)
        self.fc2 = nn.Linear(channels // reduction, 2*k)
        self.sigmoid = nn.Sigmoid()

        self.register_buffer('lambdas', torch.Tensor([1.]*k + [0.5]*k).float())
        self.register_buffer('init_v', torch.Tensor([1.] + [0.]*(2*k - 1)).float())

    def get_relu_coefs(self, x):
        theta = torch.mean(x, dim=-1)
        if self.conv_type == '2d':
            theta = torch.mean(theta, dim=-1)
        theta = self.fc1(theta)
        theta = self.relu(theta)
        theta = self.fc2(theta)
        theta = 2 * self.sigmoid(theta) - 1
        return theta

    def forward(self, x):
        raise NotImplementedError


这个函数是调用上面的计算超参数 θ ( x ) \theta(x) θ(x)部分,来实现论文中的DyReLUA:

class DyReLUA(DyReLU):
    """
    调用: self.relu = DyReLUB(64, conv_type='2d')   64=本层channels
    """
    def __init__(self, channels, reduction=4, k=2, conv_type='2d'):
        super(DyReLUA, self).__init__(channels, reduction, k, conv_type)
        self.fc2 = nn.Linear(channels // reduction, 2*k)

    def forward(self, x):
        assert x.shape[1] == self.channels
        theta = self.get_relu_coefs(x)  # 这里是执行到normalize
        relu_coefs = theta.view(-1, 2*self.k) * self.lambdas + self.init_v  # 这里是执行完 theta(x)

        # BxCxL -> LxCxBx1
        x_perm = x.transpose(0, -1).unsqueeze(-1)
        # a^k_c=relu_coefs[:, :self.k]    b^k_c=relu_coefs[:, self.k:]
        # a^k_c(x) * x_c + b^k_c(x)
        output = x_perm * relu_coefs[:, :self.k] + relu_coefs[:, self.k:]
        # LxCxBx2 -> BxCxL
        # y_c = max{a^k_c(x) * x_c + b^k_c(x)}
        result = torch.max(output, dim=-1)[0].transpose(0, -1)

        return result

这个函数是调用上面的计算超参数 θ ( x ) \theta(x) θ(x)部分,来实现论文中的DyReLUB:

class DyReLUB(DyReLU):
    def __init__(self, channels, reduction=4, k=2, conv_type='2d'):
        super(DyReLUB, self).__init__(channels, reduction, k, conv_type)
        self.fc2 = nn.Linear(channels // reduction, 2*k*channels)

    def forward(self, x):
        assert x.shape[1] == self.channels
        theta = self.get_relu_coefs(x)

        relu_coefs = theta.view(-1, self.channels, 2*self.k) * self.lambdas + self.init_v

        if self.conv_type == '1d':
            # BxCxL -> LxBxCx1
            x_perm = x.permute(2, 0, 1).unsqueeze(-1)
            output = x_perm * relu_coefs[:, :, :self.k] + relu_coefs[:, :, self.k:]
            # LxBxCx2 -> BxCxL
            result = torch.max(output, dim=-1)[0].permute(1, 2, 0)

        elif self.conv_type == '2d':
            # BxCxHxW -> HxWxBxCx1
            x_perm = x.permute(2, 3, 0, 1).unsqueeze(-1)
            output = x_perm * relu_coefs[:, :, :self.k] + relu_coefs[:, :, self.k:]
            # HxWxBxCx2 -> BxCxHxW
            result = torch.max(output, dim=-1)[0].permute(2, 3, 0, 1)

        return result

注意:我们一般不太使用DyReLUC,因为参数实在太大了。

总结

这个文件主要是一些今年来比较火或者比较新颖的一些激活函数。我比较看好的激活函数是 DyReLU和meta-AconC这两个激活函数,感兴趣的可以试试用在自己的项目里。

–2021-07-23 20:56:13

  • 28
    点赞
  • 85
    收藏
    觉得还不错? 一键收藏
  • 17
    评论
评论 17
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值