YOLOv5介绍
YOLOv5为兼顾速度与性能的目标检测算法。笔者将在近期更新一系列YOLOv5的代码导读博客。YOLOv5为2021.1.5日发布的4.0版本。
YOLOv5开源项目github网址
源代码指南摘要 URL
本博客导读的代码为utils文件夹下的activations.py最后更新日期为2021.1.7
激活函数 – 数学表达式
首先介绍YOLOv5激活函数中涉及到的函数其具体形式:
Sigmoid激活函数:
Swish激活函数:
ReLU激活函数:
ReLU6限制上述函数输出在6以内:
Hard-swish激活函数:
Swish激活函数求导过程():
tanh函数:
softplus函数(ReLU函数的平滑版):
Mish激活函数:
Mish激活函数求导过程:
然后:
activations.py
该文件定义了Yolov5中的各种激活函数。各种激活函数的表达形式及求导过程均总结如上。
# Activation functions
#定义了网络架构中使用的激活函数
import torch
import torch.nn as nn
import torch.nn.functional as F
swish类定义了Swish激活函数
# Swish https://arxiv.org/pdf/1905.02244.pdf ---
class Swish(nn.Module): #Swish激活函数
@staticmethod
def forward(x): # 此处beta定为1
return x * torch.sigmoid(x)
hardswish类定义了hardswish激活函数
class Hardswish(nn.Module): # nn.Hardswish()的输出友好版本
@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
高效应用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)
Mish类定义了Mish激活函数
# Mish https://github.com/digantamisra98/Mish ----
class Mish(nn.Module): #这里定义了Mish激活函数
@staticmethod #数学公式见上
def forward(x):
return x * F.softplus(x).tanh()
高效应用Mish激活函数的类
class MemoryEfficientMish(nn.Module): # 节省内存版
class F(torch.autograd.Function): #该类形式内容同上一个类
@staticmethod
def forward(ctx, x):
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) # sx = sigmoid(x)
fx = F.softplus(x).tanh() # fx = tanh(softplus(x))
return grad_output * (fx + x * sx * (1 - fx * fx))
def forward(self, x):
return self.F.apply(x)
定义了FReLU激活函数
# FReLU https://arxiv.org/abs/2007.11824 ---
# 旷视研究院2020ECCV 提出的激活函数 (形式真的简单)
class FReLU(nn.Module):
def __init__(self, c1, k=3): # ch_in, kernel
super().__init__()
self.conv = nn.Conv2d(c1, c1, k, 1, 1, groups=c1)
self.bn = nn.BatchNorm2d(c1)
def forward(self, x):
return torch.max(x, self.bn(self.conv(x)))
版权声明:本文为博主幻灵H_Ling原创文章,版权归属原作者,如果侵权,请联系我们删除!
原文链接:https://blog.csdn.net/weixin_42716570/article/details/113059857