首页 > 其他分享 >yolov5-7.0更改resnet主干网络

yolov5-7.0更改resnet主干网络

时间:2024-06-11 16:00:22浏览次数:23  
标签:yolov5 ch args resnet backbone else 7.0 c2 model

参考链接

ClearML教程:https://blog.csdn.net/qq_40243750/article/details/126445671

b站教学视频:https://www.bilibili.com/video/BV1Mx4y1A7jy/spm_id_from=333.788&vd_source=b52b79abfe565901e6969da2a1191407

开始

github地址:https://github.com/z1069614715/objectdetection_script/tree/master

首先安装timm库:pip install -i https://pypi.tuna.tsinghua.edu.cn/simple timm

可以查看timm中包含的所有库:timm.list_models()

报错1:

解决:直接去这个路径下,删掉__init__.py就可以了,正常来说这是一个空文件,建议删除前检查一下

步骤1:

更改models中的yolov5.py文件

导入timm库

步骤2:

更改models中的yolov5.py文件

先改309行的parse_model函数

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)

    is_backbone = False
    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
        try:
            t = m
            m = eval(m) if isinstance(m, str) else m  eval strings
        except:
            pass
        for j, a in enumerate(args):
            with contextlib.suppress(NameError):
                try:
                    args[j] = eval(a) if isinstance(a, str) else a  eval strings
                except:
                    args[j] = a

        n = n_ = max(round(n * gd), 1) if n > 1 else n  depth gain
        if m in {
                Conv, GhostConv, Bottleneck, GhostBottleneck, SPP, SPPF, DWConv, MixConv2d, Focus, CrossConv,
                BottleneckCSP, C3, 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:]]
            if m in {BottleneckCSP, C3, 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
        elif isinstance(m, str):
            t = m
            m = timm.create_model(m, pretrained=args[0], features_only=True)
            c2 = m.feature_info.channels()
        elif m in {}:
        #     m = m(*args)
        #     c2 = m.channel
        else:
            c2 = ch[f]
        if isinstance(c2, list):
            is_backbone = True
            m_ = m
            m_.backbone = True
        else:
            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 + 4 if is_backbone else 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 + 4 if is_backbone else i) for x in ([f] if isinstance(f, int) else f) if x != -1)  append to savelist
        layers.append(m_)
        if i == 0:
            ch = []
        if isinstance(c2, list):
            ch.extend(c2)
            for _ in range(5 len(ch)):
                ch.insert(0, 0)
        else:
            ch.append(c2)
    return nn.Sequential(*layers), sorted(save)

步骤3:

更改108行BaseModel类中的_forward_once函数


def _forward_once(self, x, profile=False, visualize=False):
    y, dt = [], []  # outputs
    for m in self.model:
        if m.f != -1:  # if not from previous layer
            x = y[m.f] if isinstance(m.f, int) else [x if j == -1 else y[j] for j in m.f]  # from earlier layers
        if profile:
            self._profile_one_layer(m, x, dt)
        if hasattr(m, 'backbone'):
            x = m(x)
            for _ in range(5 - len(x)):
                x.insert(0, None)
            for i_idx, i in enumerate(x):
                if i_idx in self.save:
                    y.append(i)
                else:
                    y.append(None)
            x = x[-1]
        else:
            x = m(x)  # run
            y.append(x if m.i in self.save else None)  # save output
        if visualize:
            feature_visualization(x, m.type, m.i, save_dir=visualize)
    return x

步骤4:

在model文件下创建yovov5-custom.yaml文件

# YOLOv5 

标签:yolov5,ch,args,resnet,backbone,else,7.0,c2,model
From: https://blog.csdn.net/2301_79573948/article/details/139601254

相关文章

  • yolov5模型评估指标R、P、map50怎么理解?
    R(Recall,召回率)定义:召回率是所有真实正样本中被模型正确预测为正样本的比例。计算公式:R=TP/(TP+FN),其中TP表示真正例(TruePositives),即被模型正确预测为正样本的实例;FN表示假反例(FalseNegatives),即被模型错误预测为负样本的实例。解释:召回率衡量了模型对正样本的查......
  • 【YOLOv5进阶】——修改网络结构(以C2f模块为例)
    一、站在巨人的肩膀上这里我们借鉴YOLOv8源码:上期说到,对于网络模块定义详情在common.py这个文件,如Conv、CrossConv、C3f等。本期要修改的需要参考YOLOv8里的C2f模块,它定义在YOLOv8的module文件夹的block.py文件里(与common.py一样),源码链接如下:YOLOv8源码https://github.com/u......
  • Zabbix 7.0 LTS OVF (build with LNMP based on Rocky 8.10) - VMware 虚拟机模板
    Zabbix7.0LTSOVF(buildwithLNMPbasedonRocky8.10)-VMware虚拟机模板Zabbix7.0LTS|企业级开源监控解决方案请访问原文链接:https://sysin.org/blog/zabbix-7-ovf/,查看最新版。原创作品,转载请保留出处。作者主页:sysin.orgZabbix简介全方位监控获取整个IT......
  • Zabbix 7.0 LTS - 企业级开源监控解决方案
    Zabbix7.0LTS-企业级开源监控解决方案Zabbix|TheEnterprise-ClassOpenSourceNetworkMonitoringSolution请访问原文链接:https://sysin.org/blog/zabbix-7/,查看最新版。原创作品,转载请保留出处。作者主页:sysin.orgZabbix简介全方位监控获取整个IT基础架构栈......
  • 视频图像智能识别系统 YOLOv5
    视频图像智能识别系统根据优化算法对项目现场封闭地区开展监控和防卸,对项目现场实时全天候监控识别分析,当监测到有人的身体进入时,视频图像智能识别系统会全自动警报和警示,适用三种颜色智能展现不一样情况,数据可视化监管。在项目施工作业区域开展侵入监管,如安全防护网、防护栏......
  • YOLOv5改进总目录 | backbone、Neck、head、损失函数,注意力机制上百种改进技巧
    ......
  • 【YOLOv5/v7改进系列】替换上采样层为Dysample
    一、导言介绍了一种名为DySample的超轻量级且高效的动态上采样器。DySample旨在解决当前动态上采样技术如CARAFE、FADE和SAPA虽然性能提升显著但带来大量计算负担的问题,这些问题主要来源于动态卷积的时间消耗以及用于生成动态核的额外子网络。此外,FADE和SAPA需要高分辨率特征......
  • centos7.9服务器部署nginx1.27.0
    在CentOS7.9服务器上安装带有stream模块的Nginx服务,你需要执行以下步骤:安装依赖:在开始安装Nginx之前,你需要先安装一些必要的依赖库。这包括gcc编译环境、pcre库(用于重写功能)、zlib库(用于http包内容的gzip压缩)、以及openssl库(用于通信加密)。可以使用yum命令进行安装:sudoyumin......
  • YOLOV5 配置文件
    模型配置anchors=[[(10,13),(16,30),(33,23)],#多尺度的先验框基本尺寸,(在三个尺度的特征图上放置anchors)[(30,61),(62,45),(59,119)],[(116,90),(156,198),(373,326)]]strides=[8,16,32]#先验框生成器的步幅model=dict......
  • yolov5训练日志
      (wind_2021)J:\PytorchProject\yolov5_train_car_2024060501>(wind_2021)J:\PytorchProject\yolov5_train_car_2024060501>pythontrain_20230320.py--img-size640--batch-size2--epochs300--data./data/myvoc.yaml--cfg./models/yolov5m.yaml--......