YOLOv8重要文件解读

2023-12-19 23:15
文章标签 yolov8 解读 重要文件

本文主要是介绍YOLOv8重要文件解读,希望对大家解决编程问题提供一定的参考价值,需要的开发者们随着小编来一起学习吧!

🍨 本文为[🔗365天深度学习训练营学习记录博客
🍦 参考文章:365天深度学习训练营
🍖 原作者:[K同学啊 | 接辅导、项目定制]
🚀 文章来源:[K同学的学习圈子](https://www.yuque.com/mingtian-fkmxf/zxwb45) 

D:\ultralytics-main\ultralytics-main\ultralytics\nn\models\** 目录下的文件与YOLOv5commonpy中文件起到的作用相同,对应模型中的相应模块 。

conv.py文件 

def autopad(k, p=None, d=1):  # kernel, padding, dilation"""Pad to 'same' shape outputs."""if d > 1:k = d * (k - 1) + 1 if isinstance(k, int) else [d * (x - 1) + 1 for x in k]  # actual kernel-sizeif p is None:p = k // 2 if isinstance(k, int) else [x // 2 for x in k]  # auto-padreturn p

函数的参数包括:

  • k:卷积核的大小,可以是整数或整数列表。
  • p:填充大小,可以是整数或整数列表,如果未提供,则自动计算。
  • d:膨胀率(dilation rate),默认为1。
class Conv(nn.Module):"""Standard convolution with args(ch_in, ch_out, kernel, stride, padding, groups, dilation, activation)."""default_act = nn.SiLU()  # default activationdef __init__(self, c1, c2, k=1, s=1, p=None, g=1, d=1, act=True):"""Initialize Conv layer with given arguments including activation."""super().__init__()self.conv = nn.Conv2d(c1, c2, k, s, autopad(k, p, d), groups=g, dilation=d, bias=False)self.bn = nn.BatchNorm2d(c2)self.act = self.default_act if act is True else act if isinstance(act, nn.Module) else nn.Identity()def forward(self, x):"""Apply convolution, batch normalization and activation to input tensor."""return self.act(self.bn(self.conv(x)))def forward_fuse(self, x):"""Perform transposed convolution of 2D data."""return self.act(self.conv(x))class Conv2(Conv):"""Simplified RepConv module with Conv fusing."""def __init__(self, c1, c2, k=3, s=1, p=None, g=1, d=1, act=True):"""Initialize Conv layer with given arguments including activation."""super().__init__(c1, c2, k, s, p, g=g, d=d, act=act)self.cv2 = nn.Conv2d(c1, c2, 1, s, autopad(1, p, d), groups=g, dilation=d, bias=False)  # add 1x1 convdef forward(self, x):"""Apply convolution, batch normalization and activation to input tensor."""return self.act(self.bn(self.conv(x) + self.cv2(x)))def forward_fuse(self, x):"""Apply fused convolution, batch normalization and activation to input tensor."""return self.act(self.bn(self.conv(x)))def fuse_convs(self):"""Fuse parallel convolutions."""w = torch.zeros_like(self.conv.weight.data)i = [x // 2 for x in w.shape[2:]]w[:, :, i[0]:i[0] + 1, i[1]:i[1] + 1] = self.cv2.weight.data.clone()self.conv.weight.data += wself.__delattr__('cv2')self.forward = self.forward_fuse

__init__ 方法用于初始化卷积层,参数包括输入通道数 c1,输出通道数 c2,卷积核大小 k,步幅 s,填充大小 p,分组数 g,膨胀率 d,以及是否使用激活函数 act

class LightConv(nn.Module):"""Light convolution with args(ch_in, ch_out, kernel).https://github.com/PaddlePaddle/PaddleDetection/blob/develop/ppdet/modeling/backbones/hgnet_v2.py"""def __init__(self, c1, c2, k=1, act=nn.ReLU()):"""Initialize Conv layer with given arguments including activation."""super().__init__()self.conv1 = Conv(c1, c2, 1, act=False)self.conv2 = DWConv(c2, c2, k, act=act)def forward(self, x):"""Apply 2 convolutions to input tensor."""return self.conv2(self.conv1(x))class DWConv(Conv):"""Depth-wise convolution."""def __init__(self, c1, c2, k=1, s=1, d=1, act=True):  # ch_in, ch_out, kernel, stride, dilation, activation"""Initialize Depth-wise convolution with given parameters."""super().__init__(c1, c2, k, s, g=math.gcd(c1, c2), d=d, act=act)

LightConv类

  • LightConv 类表示轻量级卷积,包含两个卷积层的堆叠。

DWConv类

  • DWConv 类表示深度可分离卷积。
  • 在初始化过程中,调用了父类 Conv__init__ 方法,其中 g 参数被设置为输入通道数和输出通道数的最大公约数,从而实现深度可分离卷积。
class DWConvTranspose2d(nn.ConvTranspose2d):"""Depth-wise transpose convolution."""def __init__(self, c1, c2, k=1, s=1, p1=0, p2=0):  # ch_in, ch_out, kernel, stride, padding, padding_out"""Initialize DWConvTranspose2d class with given parameters."""super().__init__(c1, c2, k, s, p1, p2, groups=math.gcd(c1, c2))class ConvTranspose(nn.Module):"""Convolution transpose 2d layer."""default_act = nn.SiLU()  # default activationdef __init__(self, c1, c2, k=2, s=2, p=0, bn=True, act=True):"""Initialize ConvTranspose2d layer with batch normalization and activation function."""super().__init__()self.conv_transpose = nn.ConvTranspose2d(c1, c2, k, s, p, bias=not bn)self.bn = nn.BatchNorm2d(c2) if bn else nn.Identity()self.act = self.default_act if act is True else act if isinstance(act, nn.Module) else nn.Identity()def forward(self, x):"""Applies transposed convolutions, batch normalization and activation to input."""return self.act(self.bn(self.conv_transpose(x)))def forward_fuse(self, x):"""Applies activation and convolution transpose operation to input."""return self.act(self.conv_transpose(x))
  1. DWConvTranspose2d类

    • DWConvTranspose2d 类表示深度可分离的转置卷积。
    • 在初始化过程中,调用了父类 nn.ConvTranspose2d__init__ 方法,并设置了 groups 参数为输入通道数和输出通道数的最大公约数。
  2. ConvTranspose类

    • ConvTranspose 类表示转置卷积 2D 层,与普通转置卷积相比,它包含了可选的批归一化和激活函数。
    • __init__ 方法用于初始化转置卷积,参数包括输入通道数 c1,输出通道数 c2,卷积核大小 k,步幅 s,填充参数 p,以及是否使用批归一化 bn 和激活函数 act
    • 在初始化过程中,创建了转置卷积层 conv_transpose,以及可选的批归一化层 bn 和激活函数 act
class Focus(nn.Module):"""Focus wh information into c-space."""def __init__(self, c1, c2, k=1, s=1, p=None, g=1, act=True):"""Initializes Focus object with user defined channel, convolution, padding, group and activation values."""super().__init__()self.conv = Conv(c1 * 4, c2, k, s, p, g, act=act)# self.contract = Contract(gain=2)def forward(self, x):"""Applies convolution to concatenated tensor and returns the output.Input shape is (b,c,w,h) and output shape is (b,4c,w/2,h/2)."""return self.conv(torch.cat((x[..., ::2, ::2], x[..., 1::2, ::2], x[..., ::2, 1::2], x[..., 1::2, 1::2]), 1))# return self.conv(self.contract(x))
  • Focus类(用于在通道维度上聚焦宽高信息

    • Focus 类继承自 nn.Module,表示将宽高信息集中到通道空间的操作。
    • 在初始化过程中,创建了一个包含四个输入通道的卷积层 self.conv。卷积层将四个通道的信息进行卷积操作,然后输出到通道维度上,用于集中宽高信息。
  • forward 方法:

    • forward 方法实现了前向传播操作。
    • 输入张量的形状为 (b, c, w, h),其中 b 是批量大小,c 是通道数,wh 是宽和高。
    • 通过 torch.cat 将输入张量沿着宽和高方向进行四次拼接,得到一个新的张量,形状为 (b, 4c, w/2, h/2)。
class GhostConv(nn.Module):"""Ghost Convolution https://github.com/huawei-noah/ghostnet."""def __init__(self, c1, c2, k=1, s=1, g=1, act=True):"""Initializes the GhostConv object with input channels, output channels, kernel size, stride, groups andactivation."""super().__init__()c_ = c2 // 2  # hidden channelsself.cv1 = Conv(c1, c_, k, s, None, g, act=act)self.cv2 = Conv(c_, c_, 5, 1, None, c_, act=act)def forward(self, x):"""Forward propagation through a Ghost Bottleneck layer with skip connection."""y = self.cv1(x)return torch.cat((y, self.cv2(y)), 1)

Ghost Convolution 是通过两个卷积层组合的轻量级卷积操作,其主要功能是在保持模型轻量化的同时,增加网络的感受野和表征能力。

两个卷积层组合的轻量级卷积操作:

  • 首先在初始化两个卷积层 self.cv1 = Conv(c1, c_, k, s, None, g, act=act) self.cv2 = Conv(c_, c_, 5, 1, None, c_, act=act)
  • 在forward 方法中实现两个卷积层组合:y = self.cv1(x) 将输入张量 x 传递给第一个卷积层 self.cv1 进行卷积,得到输出张量 y return torch.cat((y, self.cv2(y)), 1) 将输出张量 yself.cv2(y) 进行通道维度上的拼接,得到最终的输出。

这篇关于YOLOv8重要文件解读的文章就介绍到这儿,希望我们推荐的文章对编程师们有所帮助!



http://www.chinasem.cn/article/514046

相关文章

MySQL中的MVCC底层原理解读

《MySQL中的MVCC底层原理解读》本文详细介绍了MySQL中的多版本并发控制(MVCC)机制,包括版本链、ReadView以及在不同事务隔离级别下MVCC的工作原理,通过一个具体的示例演示了在可重... 目录简介ReadView版本链演示过程总结简介MVCC(Multi-Version Concurr

关于Gateway路由匹配规则解读

《关于Gateway路由匹配规则解读》本文详细介绍了SpringCloudGateway的路由匹配规则,包括基本概念、常用属性、实际应用以及注意事项,路由匹配规则决定了请求如何被转发到目标服务,是Ga... 目录Gateway路由匹配规则一、基本概念二、常用属性三、实际应用四、注意事项总结Gateway路由

解读Redis秒杀优化方案(阻塞队列+基于Stream流的消息队列)

《解读Redis秒杀优化方案(阻塞队列+基于Stream流的消息队列)》该文章介绍了使用Redis的阻塞队列和Stream流的消息队列来优化秒杀系统的方案,通过将秒杀流程拆分为两条流水线,使用Redi... 目录Redis秒杀优化方案(阻塞队列+Stream流的消息队列)什么是消息队列?消费者组的工作方式每

解读静态资源访问static-locations和static-path-pattern

《解读静态资源访问static-locations和static-path-pattern》本文主要介绍了SpringBoot中静态资源的配置和访问方式,包括静态资源的默认前缀、默认地址、目录结构、访... 目录静态资源访问static-locations和static-path-pattern静态资源配置

MySQL中时区参数time_zone解读

《MySQL中时区参数time_zone解读》MySQL时区参数time_zone用于控制系统函数和字段的DEFAULTCURRENT_TIMESTAMP属性,修改时区可能会影响timestamp类型... 目录前言1.时区参数影响2.如何设置3.字段类型选择总结前言mysql 时区参数 time_zon

MySQL中的锁和MVCC机制解读

《MySQL中的锁和MVCC机制解读》MySQL事务、锁和MVCC机制是确保数据库操作原子性、一致性和隔离性的关键,事务必须遵循ACID原则,锁的类型包括表级锁、行级锁和意向锁,MVCC通过非锁定读和... 目录mysql的锁和MVCC机制事务的概念与ACID特性锁的类型及其工作机制锁的粒度与性能影响多版本

Redis过期键删除策略解读

《Redis过期键删除策略解读》Redis通过惰性删除策略和定期删除策略来管理过期键,惰性删除策略在键被访问时检查是否过期并删除,节省CPU开销但可能导致过期键滞留,定期删除策略定期扫描并删除过期键,... 目录1.Redis使用两种不同的策略来删除过期键,分别是惰性删除策略和定期删除策略1.1惰性删除策略

Redis与缓存解读

《Redis与缓存解读》文章介绍了Redis作为缓存层的优势和缺点,并分析了六种缓存更新策略,包括超时剔除、先删缓存再更新数据库、旁路缓存、先更新数据库再删缓存、先更新数据库再更新缓存、读写穿透和异步... 目录缓存缓存优缺点缓存更新策略超时剔除先删缓存再更新数据库旁路缓存(先更新数据库,再删缓存)先更新数

C#反射编程之GetConstructor()方法解读

《C#反射编程之GetConstructor()方法解读》C#中Type类的GetConstructor()方法用于获取指定类型的构造函数,该方法有多个重载版本,可以根据不同的参数获取不同特性的构造函... 目录C# GetConstructor()方法有4个重载以GetConstructor(Type[]

MCU7.keil中build产生的hex文件解读

1.hex文件大致解读 闲来无事,查看了MCU6.用keil新建项目的hex文件 用FlexHex打开 给我的第一印象是:经过软件的解释之后,发现这些数据排列地十分整齐 :02000F0080FE71:03000000020003F8:0C000300787FE4F6D8FD75810702000F3D:00000001FF 把解释后的数据当作十六进制来观察 1.每一行数据