• yolo各模块详解


    1. class Conv(nn.Module):
    2. # Standard convolution with args(ch_in, ch_out, kernel, stride, padding, groups, dilation, activation)
    3. default_act = nn.SiLU() # default activation
    4. def __init__(self, c1, c2, k=1, s=1, p=None, g=1, d=1, act=True):
    5. super().__init__()
    6. self.conv = nn.Conv2d(c1, c2, k, s, autopad(k, p, d), groups=g, dilation=d, bias=False)
    7. self.bn = nn.BatchNorm2d(c2)
    8. self.act = self.default_act if act is True else act if isinstance(act, nn.Module) else nn.Identity()
    9. def forward(self, x):
    10. return self.act(self.bn(self.conv(x)))
    11. def forward_fuse(self, x):
    12. return self.act(self.conv(x))

    代码定义了一个名为Conv的类,它是nn.Module的子类。该类执行一个标准的卷积操作,可选地包括激活函数和批归一化。

    该类具有以下属性和方法:

    • default_act:这是一个类属性,设置为nn.SiLU()(Sigmoid-weighted Linear Unit),它是卷积操作中使用的默认激活函数。
    • __init__:这是构造方法,用于初始化Conv对象。它接受以下参数:
    • c1:输入通道数。
    • c2:输出通道数。
    • k:卷积核大小(默认为1)。
    • s:步长大小(默认为1)。
    • p:填充大小(默认为None)。
    • g:分组数(默认为1)。
    • d:膨胀因子(默认为1)。
    • act:激活函数或True(默认为True)。

    在这个方法中,初始化了一个Conv2d层、BatchNorm2d层和激活函数,并将它们存储为属性。

    在该方法中,首先计算隐藏通道数c_,然后初始化了三个Conv层 cv1cv2 和 cv3,其中 cv1 和 cv2 是1x1的卷积层,cv3 是具有输出通道数c2的1x1的卷积层。这些Conv层用于处理输入数据。 然后,使用nn.Sequential()初始化了一个包含n个Bottleneck模块的Sequential网络,每个Bottleneck模块的输入和输出通道数都是c_

    在该方法中,首先计算隐藏通道数c_,然后初始化了两个Conv层 cv1 和 cv2。其中 cv1 是用于处理输入张量的1x1卷积层,将输入通道数减少到c_cv2 是用于最终输出的1x1卷积层,将输入通道数增加到c2。 接下来,使用nn.MaxPool2d初始化了一个最大池化层,池化核大小为k,步长为1,填充大小为k // 2。这个最大池化层用于执行空间金字塔池化操作。

    • forward:该方法执行Conv对象的前向传播。它接受一个输入张量x,按照顺序应用卷积操作、批归一化和激活函数。然后返回输出张量。

    • forward_fuse:该方法类似于forward,但不包括批归一化。它只执行卷积操作和激活函数。然后返回输出张量。

      1. class C3(nn.Module):
      2. # CSP Bottleneck with 3 convolutions
      3. def __init__(self, c1, c2, n=1, shortcut=True, g=1, e=0.5): # ch_in, ch_out, number, shortcut, groups, expansion
      4. super().__init__()
      5. c_ = int(c2 * e) # hidden channels
      6. self.cv1 = Conv(c1, c_, 1, 1)
      7. self.cv2 = Conv(c1, c_, 1, 1)
      8. self.cv3 = Conv(2 * c_, c2, 1) # optional act=FReLU(c2)
      9. self.m = nn.Sequential(*(Bottleneck(c_, c_, shortcut, g, e=1.0) for _ in range(n)))
      10. def forward(self, x):
      11. return self.cv3(torch.cat((self.m(self.cv1(x)), self.cv2(x)), 1))

      代码定义了一个名为C3的类,它是nn.Module的子类。该类实现了一个带有3个卷积层的CSP Bottleneck结构。

      该类有以下属性和方法:

    • __init__:构造方法,用于初始化C3对象。它接受以下参数:
    • c1:输入通道数。
    • forward:该方法执行C3对象的前向传播。它接受一个输入张量x,首先将输入张量通过cv1进行卷积,然后将输入张量通过cv2进行卷积,并将两者结果进行拼接。接着将拼接后的张量作为输入传递给Sequential网络m进行处理。最后,将处理后的结果和通过cv3进行卷积的输入张量进行拼接,并返回最终的输出张量。
      • c2:输出通道数。
      • n:重复次数(默认为1)。
      • shortcut:是否使用残差连接(默认为True)。
      • g:分组数(默认为1)。
      • e:扩展系数(默认为0.5)。
        1. class SPPF(nn.Module):
        2. # Spatial Pyramid Pooling - Fast (SPPF) layer for YOLOv5 by Glenn Jocher
        3. def __init__(self, c1, c2, k=5): # equivalent to SPP(k=(5, 9, 13))
        4. super().__init__()
        5. c_ = c1 // 2 # hidden channels
        6. self.cv1 = Conv(c1, c_, 1, 1)
        7. self.cv2 = Conv(c_ * 4, c2, 1, 1)
        8. self.m = nn.MaxPool2d(kernel_size=k, stride=1, padding=k // 2)
        9. def forward(self, x):
        10. x = self.cv1(x)
        11. with warnings.catch_warnings():
        12. warnings.simplefilter('ignore') # suppress torch 1.9.0 max_pool2d() warning
        13. y1 = self.m(x)
        14. y2 = self.m(y1)
        15. return self.cv2(torch.cat((x, y1, y2, self.m(y2)), 1))

        码定义了一个名为SPPF的类,它是nn.Module的子类。该类实现了一个用于YOLOv5的SPPF(Spatial Pyramid Pooling - Fast)层。

        该类有以下属性和方法:

      • __init__:构造方法,用于初始化SPPF对象。它接受以下参数:
      • c1:输入通道数。
    • forward:该方法执行SPPF对象的前向传播。它接受一个输入张量x,首先通过cv1对输入张量进行1x1的卷积。接下来,使用最大池化层mcv1的输出张量进行多次池化操作,生成不同尺度的特征图。最后,将cv1的输出张量、池化特征图进行拼接,并通过cv2进行1x1的卷积,得到最终的输出张量。
      • c2:输出通道数。
      • k:池化核大小(默认为5)。
        1. def parse_model(d, ch): # model_dict, input_channels(3)
        2. # Parse a YOLOv5 model.yaml dictionary
        3. LOGGER.info(f"\n{'':>3}{'from':>18}{'n':>3}{'params':>10} {'module':<40}{'arguments':<30}")
        4. anchors, nc, gd, gw, act = d['anchors'], d['nc'], d['depth_multiple'], d['width_multiple'], d.get('activation')
        5. if act:
        6. Conv.default_act = eval(act) # redefine default activation, i.e. Conv.default_act = nn.SiLU()
        7. LOGGER.info(f"{colorstr('activation:')} {act}") # print
        8. na = (len(anchors[0]) // 2) if isinstance(anchors, list) else anchors # number of anchors
        9. no = na * (nc + 5) # number of outputs = anchors * (classes + 5)
        10. layers, save, c2 = [], [], ch[-1] # layers, savelist, ch out
        11. for i, (f, n, m, args) in enumerate(d['backbone'] + d['head']): # from, number, module, args
        12. m = eval(m) if isinstance(m, str) else m # eval strings
        13. for j, a in enumerate(args):
        14. with contextlib.suppress(NameError):
        15. args[j] = eval(a) if isinstance(a, str) else a # eval strings
        16. n = n_ = max(round(n * gd), 1) if n > 1 else n # depth gain
        17. if m in {
        18. Conv, GhostConv, Bottleneck, GhostBottleneck, SPP, SPPF, DWConv, MixConv2d, Focus, CrossConv,
        19. BottleneckCSP, C3, C3TR, C3SPP, C3Ghost, nn.ConvTranspose2d, DWConvTranspose2d, C3x}:
        20. c1, c2 = ch[f], args[0]
        21. if c2 != no: # if not output
        22. c2 = make_divisible(c2 * gw, 8)
        23. args = [c1, c2, *args[1:]]
        24. if m in {BottleneckCSP, C3, C3TR, C3Ghost, C3x}:
        25. args.insert(2, n) # number of repeats
        26. n = 1
        27. elif m is nn.BatchNorm2d:
        28. args = [ch[f]]
        29. elif m is Concat:
        30. c2 = sum(ch[x] for x in f)
        31. # TODO: channel, gw, gd
        32. elif m in {Detect, Segment}:
        33. args.append([ch[x] for x in f])
        34. if isinstance(args[1], int): # number of anchors
        35. args[1] = [list(range(args[1] * 2))] * len(f)
        36. if m is Segment:
        37. args[3] = make_divisible(args[3] * gw, 8)
        38. elif m is Contract:
        39. c2 = ch[f] * args[0] ** 2
        40. elif m is Expand:
        41. c2 = ch[f] // args[0] ** 2
        42. else:
        43. c2 = ch[f]
        44. m_ = nn.Sequential(*(m(*args) for _ in range(n))) if n > 1 else m(*args) # module
        45. t = str(m)[8:-2].replace('__main__.', '') # module type
        46. np = sum(x.numel() for x in m_.parameters()) # number params
        47. m_.i, m_.f, m_.type, m_.np = i, f, t, np # attach index, 'from' index, type, number params
        48. LOGGER.info(f'{i:>3}{str(f):>18}{n_:>3}{np:10.0f} {t:<40}{str(args):<30}') # print
        49. save.extend(x % i for x in ([f] if isinstance(f, int) else f) if x != -1) # append to savelist
        50. layers.append(m_)
        51. if i == 0:
        52. ch = []
        53. ch.append(c2)
        54. return nn.Sequential(*layers), sorted(save)

        代码定义了一个名为parse_model的函数,用于解析YOLOv5的model.yaml字典。

        该函数接受两个参数:d是一个包含YOLOv5模型配置信息的字典,ch是输入通道数的列表。

        函数的主要功能是根据模型配置信息解析出网络的结构,并返回一个包含所有层的nn.Sequential对象以及一个已排序的保存列表。

        具体的解析过程如下:

      • 首先从模型配置信息中提取anchors,nc,gd,gw和act等值。其中,anchors是anchor框的尺寸信息,nc是类别数,gd是深度相关的参数,gw是宽度相关的参数,act是激活函数的名称。
      • 如果act存在,则将Conv类的默认激活函数default_act重新定义为act所指定的激活函数。
      • 根据anchors的信息计算出na(anchor框的数量),并计算出no(输出的特征图通道数)。
      • 初始化layers、save和c2三个列表,用于存储每一层的模块、需要保存的层的索引和最后一个层的通道数。
      • 遍历模型配置信息中的每一层,根据模块类型和参数构建相应的模块对象,并添加到layers列表中。
      • 在遍历的过程中,根据不同的模块类型,对参数进行相应的处理。例如,对于Conv、Bottleneck、SPP等模块,需要根据通道数和深度倍数进行调整;对于Detect和Segment等模块,需要将通道数的列表作为参数传入;对于Contract和Expand等模块,需要计算通道数的改变。
      • 将每个模块对象的相关信息存储到相应的属性中,并将保存的层信息添加到save列表中。
      • 最后,返回一个nn.Sequential对象,其中包含所有的模块,以及一个已排序的保存列表。
  • 相关阅读:
    存储资源盘活系统,“盘活”物联网架构难题(下)
    解决kkFileView4.4.0版本pdf、word不能预览问题
    混凝土基础的智能设计:VisualFoundation 12.0 Crack
    Swagger有哪些非常重要的注释?
    传输层协议(TCP/UDP协议)
    【MySQL从入门到精通】【高级篇】(十一)Hash索引、AVL树、B树与B+树对比
    Vue3-初识Vue3、创建Vue3工程、vue3组合式API(setup、ref函数、reactive函数)、响应式原理、计算属性、监视属性
    从Opencv之图像直方图源码,探讨高性能计算设计思想
    如何避免邮件被识别为垃圾邮件
    网络攻击的常见形式
  • 原文地址:https://blog.csdn.net/qq_53821866/article/details/134291961