修改YOLOv5的模型结构第三弹

news/2024/7/7 21:41:08
  • 🍨 本文为🔗365天深度学习训练营 中的学习记录博客
  • 🍖 原作者:K同学啊 | 接辅导、项目定制
  • 🚀 文章来源:K同学的学习圈子

    文章目录

    • 任务
      • 任务拆解
    • 开始修改
      • C2模块
      • 修改yolo.py
      • 修改模型配置文件
    • 模型训练

上次已经做了一个对YOLOv5的魔改任务,这次继续魔改。使用的素材还是之前说到的C2模块,但这次会对模型进行范围更大的修改

任务

将原模型修改为新模型
原模型如图:
原模型
新模型如图:
新模型

任务拆解

首先分析两个模型之间的改动有哪些

  • 第4层的C3*2修改为了C2*2
  • 第6层的C3*3修改为了C3*1
  • 移除了第7层的卷积
  • 移除了第8层的C3*1

其中C2模块是由C3模块修改而来,在之前的博客中也提到过,这里贴下图
C2模块

开始修改

C2模块

首先还是要先编写一个C2模块。打开models/common.py在class C3附近新建一个我们的C2模块

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

    def forward(self, x):
        return self.cv3(torch.cat((self.m(self.cv1(x)), self.cv2(x)), 1))

class C2(nn.Module):
    def __init__(self, c1, c2, n=1, shortcut=True, g=1, e=0.5):
        super().__init__()
        c_1 = c2 // 2
        c_2 = c2 - c_1
        self.cv1 = Conv(c1, c_2, 1, 1)
        self.cv2 = Conv(c1, c_1, 1, 1)
        self.m = nn.Sequential(*(Bottleneck(c_2, c_2, shortcut, g, e=1.0) for _ in range(n)))

    def forward(self, x):
        return torch.cat((self.m(self.cv1(x)), self.cv2(x)), 1)

修改yolo.py

修改yolo.py中函数parse_model中的代码,使模型支持我们刚写的C2模块

def parse_model(d, ch):  # model_dict, input_channels(3)
    # Parse a YOLOv5 model.yaml dictionary
    LOGGER.info(f"\n{'':>3}{'from':>18}{'n':>3}{'params':>10}  {'module':<40}{'arguments':<30}")
    anchors, nc, gd, gw, act = d['anchors'], d['nc'], d['depth_multiple'], d['width_multiple'], d.get('activation')
    if act:
        Conv.default_act = eval(act)  # redefine default activation, i.e. Conv.default_act = nn.SiLU()
        LOGGER.info(f"{colorstr('activation:')} {act}")  # print
    na = (len(anchors[0]) // 2) if isinstance(anchors, list) else anchors  # number of anchors
    no = na * (nc + 5)  # number of outputs = anchors * (classes + 5)

    layers, save, c2 = [], [], ch[-1]  # layers, savelist, ch out
    for i, (f, n, m, args) in enumerate(d['backbone'] + d['head']):  # from, number, module, args
        m = eval(m) if isinstance(m, str) else m  # eval strings
        for j, a in enumerate(args):
            with contextlib.suppress(NameError):
                args[j] = eval(a) if isinstance(a, str) else a  # eval strings

        n = n_ = max(round(n * gd), 1) if n > 1 else n  # depth gain
        # 在这个集合中增加了C2模块
        if m in {
                Conv, GhostConv, Bottleneck, GhostBottleneck, SPP, SPPF, DWConv, MixConv2d, Focus, CrossConv,
                BottleneckCSP, C3, C2, C3TR, C3SPP, C3Ghost, nn.ConvTranspose2d, DWConvTranspose2d, C3x}: 
            c1, c2 = ch[f], args[0]
            if c2 != no:  # if not output
                c2 = make_divisible(c2 * gw, 8)

            args = [c1, c2, *args[1:]]
            # 这这个集合中也增加了C2模块
            if m in {BottleneckCSP, C3, C2, C3TR, C3Ghost, C3x}: 
                args.insert(2, n)  # number of repeats
                n = 1
        elif m is nn.BatchNorm2d:
            args = [ch[f]]
        elif m is Concat:
            c2 = sum(ch[x] for x in f)
        # TODO: channel, gw, gd
        elif m in {Detect, Segment}:
            args.append([ch[x] for x in f])
            if isinstance(args[1], int):  # number of anchors
                args[1] = [list(range(args[1] * 2))] * len(f)
            if m is Segment:
                args[3] = make_divisible(args[3] * gw, 8)
        elif m is Contract:
            c2 = ch[f] * args[0] ** 2
        elif m is Expand:
            c2 = ch[f] // args[0] ** 2
        else:
            c2 = ch[f]

        m_ = nn.Sequential(*(m(*args) for _ in range(n))) if n > 1 else m(*args)  # module
        t = str(m)[8:-2].replace('__main__.', '')  # module type
        np = sum(x.numel() for x in m_.parameters())  # number params
        m_.i, m_.f, m_.type, m_.np = i, f, t, np  # attach index, 'from' index, type, number params
        LOGGER.info(f'{i:>3}{str(f):>18}{n_:>3}{np:10.0f}  {t:<40}{str(args):<30}')  # print
        save.extend(x % i for x in ([f] if isinstance(f, int) else f) if x != -1)  # append to savelist
        layers.append(m_)
        if i == 0:
            ch = []
        ch.append(c2)
    return nn.Sequential(*layers), sorted(save)

修改模型配置文件

参考models/yolov5s.yaml来修改模型的配置
对照着刚才识别到的改动来操作

  1. 第4层的C3*2修改为了C2*2
    将backbone下面的数组第4个元素中的C3修改为C2
# 旧
   [-1, 6, C3, [256]],
# 新
   [-1, 6, C2, [256]],
  1. 第6层的C3*3修改为了C3*1
    将backbone下面的数组第6个元素中的 number由9修改为3
# 旧
   [-1, 9, C3, [512]],
# 新
   [-1, 3, C3, [512]]
  1. 移除了第7层的卷积
  2. 移除了第8层的C3*1
    删除backbone中第7个和第8个元素
   [-1, 1, Conv, [1024, 3, 2]],  # 7-P5/32
   [-1, 3, C3, [1024]],

修改到当前这一步,我以为就已经完成了,但是实际上只完成了一半。
通过对前面知识的回顾,Concat模块会引用上层的模块的输出,体现在配置文件中,就是会引用数组中的下标,但是我们在数组中删除了两个元素,会使数组原本的索引失效。
通过上面的模型结构图也可以发现,删除两层后,6层以后的下标都要减2。于是修改配置文件中的head下面的配置

# YOLOv5 v6.0 head
head:
  [[-1, 1, Conv, [512, 1, 1]],
   [-1, 1, nn.Upsample, [None, 2, 'nearest']],
   [[-1, 6], 1, Concat, [1]],  # 6 不用修改
   [-1, 3, C3, [512, False]],  # 13

   [-1, 1, Conv, [256, 1, 1]],
   [-1, 1, nn.Upsample, [None, 2, 'nearest']],
   [[-1, 4], 1, Concat, [1]],  # 4 不用修改
   [-1, 3, C3, [256, False]],  # 17 (P3/8-small)

   [-1, 1, Conv, [256, 3, 2]],
   [[-1, 14], 1, Concat, [1]],  # 原来的14现在是12了
   [-1, 3, C3, [512, False]],  # 20 (P4/16-medium)

   [-1, 1, Conv, [512, 3, 2]],
   [[-1, 10], 1, Concat, [1]],  # 原来的10现在是8了
   [-1, 3, C3, [1024, False]],  # 23 (P5/32-large)

   [[17, 20, 23], 1, Detect, [nc, anchors]],  # 原来的17,20,23对应现在的15,18,21
  ]

如此改完后,我又一次认为已经完成了,但是跑了一下却报错了。如图:
报错图
通过错误信息可以发现是特征图的维度不一致导致的。于是回头分析我们所有的改动,C2模块天生就和C3模块的输入和输出维度一样,所有可以无缝替换、增加到模型中。另外之所以可以实现C3*n的效果,就是因为单个模块的输入和输出也一样。
所以问题不会出现在对C3->C2的改动。剩下的就是删除了两层中有一层是卷积。于是回头看了一下删除的卷积的,[-1, 1, Conv, [1024, 3, 2]],它的kernelsize是3,stride是2,这是一个会让特征图的尺寸缩小一半的卷积,由于我们删除了它,后面的流程中特征图的尺寸会和原来有所不同,最终导致错误。我们需要想办法弥补这个差异。
在head的第一层中,使用了一个1x1的卷积,我们把它修改为kernelsize=3,stride=2的卷积。

# 前
head:
  [[-1, 1, Conv, [512, 1, 1]],
# 后
head:
  [[-1, 1, Conv, [512, 3, 2]],

最终模型配置文件被修改为

# YOLOv5 🚀 by Ultralytics, AGPL-3.0 license

# Parameters
nc: 80  # number of classes
depth_multiple: 0.33  # model depth multiple
width_multiple: 0.50  # layer channel multiple
anchors:
  - [10,13, 16,30, 33,23]  # P3/8
  - [30,61, 62,45, 59,119]  # P4/16
  - [116,90, 156,198, 373,326]  # P5/32

# YOLOv5 v6.0 backbone
backbone:
  # [from, number, module, args]
  [[-1, 1, Conv, [64, 6, 2, 2]],  # 0-P1/2
   [-1, 1, Conv, [128, 3, 2]],  # 1-P2/4
   [-1, 3, C3, [128]],
   [-1, 1, Conv, [256, 3, 2]],  # 3-P3/8
   [-1, 6, C2, [256]],
   [-1, 1, Conv, [512, 3, 2]],  # 5-P4/16
   [-1, 3, C3, [512]],
   [-1, 1, SPPF, [1024, 5]],  # 7
  ]

# YOLOv5 v6.0 head
head:
  [[-1, 1, Conv, [512, 3, 2]],                        # 8 必须使用stride=2来弥补backbone中删除的卷积,不然后面特征图的尺寸对不上
   [-1, 1, nn.Upsample, [None, 2, 'nearest']],        # 9
   [[-1, 6], 1, Concat, [1]],  # cat backbone P4       10
   [-1, 3, C3, [512, False]],  #                       11

   [-1, 1, Conv, [256, 1, 1]], #                       12
   [-1, 1, nn.Upsample, [None, 2, 'nearest']], #       13
   [[-1, 4], 1, Concat, [1]],  # cat backbone P3       14
   [-1, 3, C3, [256, False]],  #  (P3/8-small)         15

   [-1, 1, Conv, [256, 3, 2]],                       # 16
   [[-1, 12], 1, Concat, [1]], # cat head P4           17
   [-1, 3, C3, [512, False]],  # (P4/16-medium)        18

   [-1, 1, Conv, [512, 3, 2]],                       # 19
   [[-1, 8], 1, Concat, [1]], # cat head P5            20
   [-1, 3, C3, [1024, False]], #  (P5/32-large)        21

   [[15, 18, 21], 1, Detect, [nc, anchors]],  # Detect(P3, P4, P5)
  ]

模型训练

所有的修改至此就完成了,使用train.py脚本训练一下修改后的模型。结果如图:

模型训练结果图


http://lihuaxi.xjx100.cn/news/1829165.html

相关文章

python编写简单登录系统(密码混淆加密)

输入非123的数字会显示输入123选项&#xff0c;输入空格或者回车会报错&#xff0c;因为choice设置成int型先输入2个正常账户进去预防了用户名为空&#xff0c;密码为空或者小于3个&#xff0c;用户名已存在3种情况只有用户名和对应的密码都输入正确才能登录成功输入选项3退出代…

OpenCV快速入门:特征点检测与匹配

文章目录 前言一、角点检测1.1 角点特征1.1.1 角点特征概念1.1.2 角点的特点1.1.3 关键点绘制代码实现1.1.4 函数解析 1.2 Harris角点检测1.2.1 Harris角点检测原理1.2.2 Harris角点检测公式1.2.3 代码实现1.2.4 函数解析 1.3 Shi-Tomasi角点检测1.3.1 Shi-Tomasi角点检测原理1…

【模拟开关CH440R】2022-1-20

资料模拟开关CH440芯片手册 - 百度文库 ch440R回来了&#xff0c;导通usb设备没问题&#xff0c;降压不影响。但是我发现个严重的问题&#xff0c;我的电路是直接通过4067控制ch440r接地&#xff0c;低电平&#xff0c;使能三个线路连一起的&#xff0c;邮箱的图您看看&#xf…

Java21虚拟线程实践

Java21虚拟线程实践 一个月之前&#xff0c;java21正式版发布了&#xff0c;作为继java17之后的又一个长期支持版本 (LTS)&#xff0c;为我们带来了很多新的特性&#xff0c;其中我最感兴趣的就是虚拟线程(virtual thread)&#xff0c;相信大家对虚拟线程也很好奇。趁着空闲时…

五种多目标优化算法(NSDBO、NSGA3、MOGWO、NSWOA、MOPSO)求解微电网多目标优化调度(MATLAB代码)

一、多目标优化算法简介 &#xff08;1&#xff09;非支配排序的蜣螂优化算法NSDBO 多目标应用&#xff1a;基于非支配排序的蜣螂优化算法NSDBO求解微电网多目标优化调度&#xff08;MATLAB&#xff09;-CSDN博客 &#xff08;2&#xff09;NSGA3 NSGA-III求解微电网多目标…

c++ 库中string的简单实现

文章目录 string构造函数string()拷贝构造string()长度size()下标引用[]//返回这个字符串类型间的转化c_str迭代器iterator、begin、endprint打印扩容reservepush_bacak尾插append尾插入一个字符串尾部插入 赋值insert在pos位置插入一个字符或者字符串erase从pos位置开始删除le…

Echarts仪表盘3.0

代码&#xff1a; <html> <head><title>图表绘制</title><style type"text/css">#dashboard {width: 402px;height: 293px;margin: 50px auto;}</style> </head> <body><!-- 为ECharts准备一个具备大小&#xf…

“三个绝技“让项目经理轻松做好进度管理

大家好&#xff0c;我是老原。 我离开腾讯之后&#xff0c;曾经加入一家互联网创业公司。 要知道&#xff0c;当你在一个大公司的平台上做事做习惯之后&#xff0c;觉得一些流程都应该是严谨的、完备的、按计划进行的。 但是当时&#xff0c;经常出现一个致命问题——进度拖…