第Y5周:yolo.py文件解读

article/2025/7/14 1:13:15
  • 🍨 本文为🔗365天深度学习训练营 中的学习记录博客
  • 🍖 原作者:K同学啊

本次任务:将YOLOv5s网络模型中的C3模块按照下图方式修改形成C2模块,并将C2模块插入第2层与第3层之间,且跑通YOLOv5s。
任务提示:
提示1:需要修改common.yaml、yolo.py、yolov5s.yaml文件。
提示2:C2模块与C3模块是非常相似的两个模块,我们要插入C2到模型当中,只需要找到哪里有C3模块,然后在其附近加上C2即可。
在这里插入图片描述
在这里插入图片描述
在这里插入图片描述

文章目录

  • 1、前言
  • 2、导入需要的包和基本配置
  • 3、parse_model函数
  • 4、Detect类
  • 5、Model类
  • 6、文件修改
    • 1、./models/common.py 增加C2模块
    • 2、./models/yolo.py 在parse_model中增加C2
    • 3、./models/yolov5s.yaml 在原第2层和原第3层之间插入C2模块
    • 4、训练

1、前言

文件位置:./models/yolo.py

这个文件是YOLOv5网络模型的搭建文件。如果需要改进YOLOv5,这个文件就是必须修改的文件之一。文件内容看起来多,真正有用的代码不多,重点理解好稳重提到的一个函数和两个类即可。

注: 由于YOLOv5版本众多,同一个文件对于细节处可能会看到不同的版本,不用担心这是正常的,注意把握好整体架构即可。

2、导入需要的包和基本配置

# Ultralytics 🚀 AGPL-3.0 License - https://ultralytics.com/license
"""
YOLO-specific modules.Usage:$ python models/yolo.py --cfg yolov5s.yaml
"""import argparse
import contextlib
import math
import os
import platform
import sys
from copy import deepcopy
from pathlib import Pathimport torch
import torch.nn as nnFILE = Path(__file__).resolve()
ROOT = FILE.parents[1]  # YOLOv5 root directory
if str(ROOT) not in sys.path:sys.path.append(str(ROOT))  # add ROOT to PATH
if platform.system() != "Windows":ROOT = Path(os.path.relpath(ROOT, Path.cwd()))  # relativefrom models.common import *
from models.experimental import *
from utils.autoanchor import check_anchor_order
from utils.general import LOGGER, check_version, check_yaml, colorstr, make_divisible, print_args
from utils.plots import feature_visualization
from utils.torch_utils import (fuse_conv_and_bn,initialize_weights,model_info,profile,scale_img,select_device,time_sync,
)try:import thop  # for FLOPs computation
except ImportError:thop = None

3、parse_model函数

这个函数用于将模型的模块拼接起来,搭建完成的网络模型。后续如果需要动模型框架的话,你需要对这个函数做相应的改动。

def parse_model(d, ch):  # model_dict, input_channels(3)# Parse a YOLOv5 model.yaml dictionary''' 用在上面DetectionModel模块中解析模型文件(字典形式),并搭建网络结构这个函数其实主要做的就是:更新当前层的args(参数),计算c2(当前层的输出channel)->使用当前层的参数搭建当前层->生成 layers + save:params d: model_dict模型文件,字典形式{dice: 7}(yolov5s.yaml中的6个元素 + ch):params ch: 记录模型每一层的输出channel,初始ch=[3],后面会删除:return nn.Sequential(*layers): 网络的每一层的层结构:return sorted(save): 把所有层结构中的from不是-1的值记下,并排序[4,6,10,14,17,20,23]'''LOGGER.info(f"\n{'':>3}{'from':>18}{'n':>3}{'params':>10}  {'module':<40}{'arguments':<30}")# 读取字典d中的anchors和parameters(nc,depth_multiple,width_multiple)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: number of anchors 每一个predict head上的anchor数=3na = (len(anchors[0]) // 2) if isinstance(anchors, list) else anchors  # number of anchors# no: number of outputs 每一个predict head层的输出channel=anchors*(classes+5)=75(VOC)no = na * (nc + 5)  # number of outputs = anchors * (classes + 5)''' 开始搭建网络layers: 保存每一层的层结构save: 记录下所有层结构中from不是-1的层结构序号c2: 保存当前层的输出channel'''layers, save, c2 = [], [], ch[-1]  # layers, savelist, ch out# from: 当前层输入来自哪些层# number: 当前层数,初定# module: 当前层类别# args: 当前层类参数,初定# 遍历backbone和head的每一层for i, (f, n, m, args) in enumerate(d['backbone'] + d['head']):  # from, number, module, args# 得到当前层的真实类名,例如:m = Focus -> <class 'models.common.Focus'>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# --------------------更新当前层的args(参数),计算c2(当前层的输出channel)--------------------# depth gain 控制深度,如yolov5s: n*0.33,n: 当前模块的次数(间接控制深度)n = n_ = max(round(n * gd), 1) if n > 1 else n  # depth gainif m in {Conv, GhostConv, Bottleneck, GhostBottleneck, SPP, SPPF, DWConv, MixConv2d, Focus, CrossConv,BottleneckCSP, C3, C3TR, C3SPP, C3Ghost, nn.ConvTranspose2d, DWConvTranspose2d, C3x}:# c1: 当前层的输入channel数; c2: 当前层的输出channel数(初定); ch: 记录着所有层的输出channel数c1, c2 = ch[f], args[0]# no=75,只有最后一层c2=no,最后一层不用控制宽度,输出channel必须是noif c2 != no:  # if not output# width gain 控制宽度,如yolov5s: c2*0.5; c2: 当前层的最终输出channel数(间接控制宽度)c2 = make_divisible(c2 * gw, 8)# 在初始args的基础上更新,加入当前层的输入channel并更新当前层# [in_channels, out_channels, *args[1:]]args = [c1, c2, *args[1:]]# 如果当前层是BottleneckCSP/C3/C3TR/C3Ghost/C3x,则需要在args中加入Bottleneck的个数# [in_channels, out_channels, Bottleneck个数, Bool(shortcut有无标记)]if m in {BottleneckCSP, C3, C3TR, C3Ghost, C3x}:args.insert(2, n)  # number of repeats 在第二个位置插入Bottleneck的个数nn = 1 # 恢复默认值1elif m is nn.BatchNorm2d:# BN层只需要返回上一层的输出channelargs = [ch[f]]elif m is Concat:# Concat层则将f中所有的输出累加得到这层的输出channelc2 = sum(ch[x] for x in f)# TODO: channel, gw, gdelif m in {Detect, Segment}:  # Detect/Segment(YOLO Layer)层# 在args中加入三个Detect层的输出channelargs.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] ** 2elif m is Expand:  # 不怎么用c2 = ch[f] // args[0] ** 2else:  # Upsamplec2 = ch[f]  # args不变# -------------------------------------------------------------------------------------------# m_: 得到当前层的module,如果n>1就创建多个m(当前层结构),如果n=1就创建一个mm_ = nn.Sequential(*(m(*args) for _ in range(n))) if n > 1 else m(*args)  # module# 打印当前层结构的一些基本信息t = str(m)[8:-2].replace('__main__.', '')  # module type  <'modules.common.Focus'>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 paramsLOGGER.info(f'{i:>3}{str(f):>18}{n_:>3}{np:10.0f}  {t:<40}{str(args):<30}')  # print# 把所有层结构中的from不是-1的值记下 [6,4,14,10,17,20,23]save.extend(x % i for x in ([f] if isinstance(f, int) else f) if x != -1)  # append to savelist# 将当前层结构module加入layers中layers.append(m_)if i == 0:ch = []  # 去除输入channel[3]# 把当前层的输出channel数加入chch.append(c2)return nn.Sequential(*layers), sorted(save)

4、Detect类

Detect模块是用来构建Detect层的,将输入的feature map通过一个卷积操作和公式计算到我们想要的shape,为后面的计算损失率或者NMS做准备。

Detect类代码如下:

class Detect(nn.Module):# YOLOv5 Detect head for detection models''' Detect模块是用来构建Detect层的将输入的feature map通过一个卷积操作和公式计算到我们想要的shape,为后面的计算损失率或者NMS做准备'''stride = None  # strides computed during builddynamic = False  # force grid reconstructionexport = False  # export modedef __init__(self, nc=80, anchors=(), ch=(), inplace=True):  # detection layer''' detection layer 相当于yolov3中的YOLO Layer层:params nc: number of classes:params anchors: 传入3个feature map上的所有anchor的大小(P3/P4/P5):params ch: [128,256,512] 3个输出feature map的channel'''super().__init__()self.nc = nc  # number of classes  VOC: 20self.no = nc + 5  # number of outputs per anchor  VOC: 5(xywhc)+20(classes)=25self.nl = len(anchors)  # number of detection layers  Detect的个数=3self.na = len(anchors[0]) // 2  # number of anchors  每个feature map的anchor个数=3self.grid = [torch.empty(0) for _ in range(self.nl)]  # init grid  {list: 3} tensor([0.])X3self.anchor_grid = [torch.empty(0) for _ in range(self.nl)]  # init anchor grid'''  模型中需要保存的参数一般有两种:一种是反向传播需要被optimizer更新的,称为parameter;另一种不需要被更新,称为bufferbuffer的参数更新是在forward中,而optim.step只能更新nn.parameter参数'''self.register_buffer('anchors', torch.tensor(anchors).float().view(self.nl, -1, 2))  # shape(nl,na,2)# output conv 对每个输出的feature map都要调用一次conv1 x 1self.m = nn.ModuleList(nn.Conv2d(x, self.no * self.na, 1) for x in ch)  # output conv# 一般都是True,默认不使用AWS,Inferentia加速self.inplace = inplace  # use inplace ops (e.g. slice assignment)def forward(self, x):''':return train: 一个tensor list,存放三个元素[bs, anchor_num, grid_w, grid_h, xywh+c+classes]分别是[1,3,80,80,25] [1,3,40,40,25] [1,3,20,20,25]inference: 0 [1,19200+4800+1200,25]=[bs,anchor_num*grid_w*grid_h,xywh+c+classes]'''z = []  # inference outputfor i in range(self.nl):  # 对3个feature map分别进行处理x[i] = self.m[i](x[i])  # conv  xi[bs,128/256/512,80,80] to [bs,75,80,80]bs, _, ny, nx = x[i].shape  # x(bs,255,20,20) to x(bs,3,20,20,85)# [bs,75,80,80] to [1,3,25,80,80] to [1,3,80,80,25]x[i] = x[i].view(bs, self.na, self.no, ny, nx).permute(0, 1, 3, 4, 2).contiguous()''' 构造网格因为推理返回的不是归一化后的网络偏移量,需要加上网格的位置,得到最终的推理坐标,再送入NMS所以这里构建网络就是为了记录每个grid的网格坐标,方便后面使用'''if not self.training:  # inferenceif self.dynamic or self.grid[i].shape[2:4] != x[i].shape[2:4]:self.grid[i], self.anchor_grid[i] = self._make_grid(nx, ny, i)if isinstance(self, Segment):  # (boxes + masks)xy, wh, conf, mask = x[i].split((2, 2, self.nc + 1, self.no - self.nc - 5), 4)xy = (xy.sigmoid() * 2 + self.grid[i]) * self.stride[i]  # xywh = (wh.sigmoid() * 2) ** 2 * self.anchor_grid[i]  # why = torch.cat((xy, wh, conf.sigmoid(), mask), 4)else:  # Detect (boxes only)xy, wh, conf = x[i].sigmoid().split((2, 2, self.nc + 1), 4)xy = (xy * 2 + self.grid[i]) * self.stride[i]  # xywh = (wh * 2) ** 2 * self.anchor_grid[i]  # why = torch.cat((xy, wh, conf), 4)# z是一个tensor list,有三个元素,分别是[1,19200,25] [1,4800,25] [1,1200,25]z.append(y.view(bs, self.na * nx * ny, self.no))return x if self.training else (torch.cat(z, 1),) if self.export else (torch.cat(z, 1), x)def _make_grid(self, nx=20, ny=20, i=0, torch_1_10=check_version(torch.__version__, '1.10.0')):''' 构造网格 '''d = self.anchors[i].devicet = self.anchors[i].dtypeshape = 1, self.na, ny, nx, 2  # grid shapey, x = torch.arange(ny, device=d, dtype=t), torch.arange(nx, device=d, dtype=t)yv, xv = torch.meshgrid(y, x, indexing='ij') if torch_1_10 else torch.meshgrid(y, x)  # torch>=0.7 compatibilitygrid = torch.stack((xv, yv), 2).expand(shape) - 0.5  # add grid offset, i.e. y = 2.0 * x - 0.5anchor_grid = (self.anchors[i] * self.stride[i]).view((1, self.na, 1, 1, 2)).expand(shape)return grid, anchor_grid

5、Model类

这个模块是整个模型的搭建模块。且yolov5的作者将这个模块的功能写的很全,不光包含模型的搭建,还扩展了很多功能,如:特征可视化、打印模型信息、TTA推理增强、融合Conv + BN加速推理、模型搭载NMS功能、Autoshape函数(模型包含前处理、推理、后处理的模块(预处理 + 推理 + NMS))。感兴趣的可以仔细看看,不感兴趣的可以直接看__init__、forward两个函数即可。

Model类代码如下:

class BaseModel(nn.Module):# YOLOv5 base modeldef forward(self, x, profile=False, visualize=False):return self._forward_once(x, profile, visualize)  # single-scale inference, traindef _forward_once(self, x, profile=False, visualize=False):''':params x: 输入图像:params profile: True 可以做一些性能评估:params visualize: True 可以做一些特征可视化:return train: 一个tensor,存放三个元素 [bs, anchor_num, grid_w, grid_h, xywh+c+classes]inference: 0 [1,19200+4800+1200,25]=[bs,anchor_num*grid_w*grid_h,xywh+c+classes]'''# y: 存放着self.save=True的每一层的输出,因为后面的层结构Concat等操作要用到# dt: 在profile中做性能评估时使用y, dt = [], []  # outputsfor m in self.model:# 前向推理每一层结构 m.i=index; m.f=from; m.type=类名; m.np=number of parametersif m.f != -1:  # if not from previous layer  m.f=当前层的输入来自哪一层的输出,-1表示上一层# 这里需要做4个Concat操作和一个Detect操作# Concat: 如m.f=[-1,6] x就有两个元素,一个是上一层的输出,一个是index=6的层的输出,再送到x=m(x)做Concat操作# Detect: 如m.f=[17, 20, 23] x就有三个元素,分别存放第17层第20层第23层的输出,再送到x=m(x)做Detect的forwardx = y[m.f] if isinstance(m.f, int) else [x if j == -1 else y[j] for j in m.f]  # from earlier layers# 打印日志信息  FLOPs time等if profile:self._profile_one_layer(m, x, dt)x = m(x)  # run  正向推理# 存放着self.save的每一层的输出,因为后面需要用来做Concat等操作,不在self.save层的输出就为Noney.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 xdef _profile_one_layer(self, m, x, dt):c = m == self.model[-1]  # is final layer, copy input as inplace fixo = thop.profile(m, inputs=(x.copy() if c else x,), verbose=False)[0] / 1E9 * 2 if thop else 0  # FLOPst = time_sync()for _ in range(10):m(x.copy() if c else x)dt.append((time_sync() - t) * 100)if m == self.model[0]:LOGGER.info(f"{'time (ms)':>10s} {'GFLOPs':>10s} {'params':>10s}  module")LOGGER.info(f'{dt[-1]:10.2f} {o:10.2f} {m.np:10.0f}  {m.type}')if c:LOGGER.info(f"{sum(dt):10.2f} {'-':>10s} {'-':>10s}  Total")def fuse(self):  # fuse model Conv2d() + BatchNorm2d() layers''' 用在detect.py、val.py中fuse model Conv2d() + BatchNorm2d() layers调用torch_utils.py中的fuse_conv_and_bn函数和common.py中的forward_fuse函数'''LOGGER.info('Fusing layers... ')  # 日志for m in self.model.modules():  # 遍历每一层结构# 如果当前层是卷积层Conv且有BN结构,那么就调用fuse_conv_and_bn函数将Conv和BN进行融合,加速推理if isinstance(m, (Conv, DWConv)) and hasattr(m, 'bn'):m.conv = fuse_conv_and_bn(m.conv, m.bn)  # update conv  融合delattr(m, 'bn')  # remove batchnorm  移除BNm.forward = m.forward_fuse  # update forward  更新前向传播(反向传播不用管,因为这个过程只用再推理阶段)self.info()  # 打印Conv+BN融合后的模型信息return selfdef info(self, verbose=False, img_size=640):  # print model information''' 用在上面的__init__函数上调用torch_utils.py下model_info函数打印模型信息'''model_info(self, verbose, img_size)def _apply(self, fn):# Apply to(), cpu(), cuda(), half() to model tensors that are not parameters or registered buffersself = super()._apply(fn)m = self.model[-1]  # Detect()if isinstance(m, (Detect, Segment)):m.stride = fn(m.stride)m.grid = list(map(fn, m.grid))if isinstance(m.anchor_grid, list):m.anchor_grid = list(map(fn, m.anchor_grid))return selfclass DetectionModel(BaseModel):# YOLOv5 detection modeldef __init__(self, cfg='yolov5s.yaml', ch=3, nc=None, anchors=None):  # model, input channels, number of classes''':params cfg: 模型配置文件:params ch: input img channels 一般是3(RGB文件):params nc: number of classes 数据集的类别个数:params anchors: 一般是None'''super().__init__()if isinstance(cfg, dict):self.yaml = cfg  # model dictelse:  # is *.yaml  一般执行这里import yaml  # for torch hubself.yaml_file = Path(cfg).name  # cfg file name = 'yolov5s.yaml'# 如果配置文件中有中文,打开时要加encoding参数with open(cfg, encoding='ascii', errors='ignore') as f:  # encoding='utf-8'self.yaml = yaml.safe_load(f)  # model dict# Define modelch = self.yaml['ch'] = self.yaml.get('ch', ch)  # input channels  ch=3# 设置类别数,一般不执行,因为nc=self.yaml['nc']恒成立if nc and nc != self.yaml['nc']:LOGGER.info(f"Overriding model.yaml nc={self.yaml['nc']} with nc={nc}")self.yaml['nc'] = nc  # override yaml value# 重写anchors,一般不执行,因为传进来的anchors一般都是Noneif anchors:LOGGER.info(f'Overriding model.yaml anchors with anchors={anchors}')self.yaml['anchors'] = round(anchors)  # override yaml value# 创建网络模型# self.model: 初始化的整个网络模型(包括Detect层结构)# self.save: 所有层结构中from不等于-1的序号,并排好序  [4,6,10,14,17,20,23]self.model, self.save = parse_model(deepcopy(self.yaml), ch=[ch])  # model, savelist# default class names ['0','1','2',...,'19']self.names = [str(i) for i in range(self.yaml['nc'])]  # default names# self.inplace=True  默认True,不使用加速推理# AWS Inferentia Inplace compatiability# https://github.com/ultralytics/yolov5/pull/2953self.inplace = self.yaml.get('inplace', True)# Build strides, anchors# 获取Detect模块的stride(相对输入图像的下采样率)和anchors在当前Detect输出的feature map的尺寸m = self.model[-1]  # Detect()if isinstance(m, (Detect, Segment)):s = 256  # 2x min stridem.inplace = self.inplaceforward = lambda x: self.forward(x)[0] if isinstance(m, Segment) else self.forward(x)# 计算三个feature map的anchor大小,如[10,13]/8 -> [1.25,1.625]m.stride = torch.tensor([s / x.shape[-2] for x in forward(torch.zeros(1, ch, s, s))])  # forward# 检查anchor顺序与stride顺序是否一致check_anchor_order(m)m.anchors /= m.stride.view(-1, 1, 1)self.stride = m.strideself._initialize_biases()  # only run once  初始化偏置# Init weights, biasesinitialize_weights(self)  # 调用torch_utils.py下initialize_weights初始化模型权重self.info()  # 打印模型信息LOGGER.info('')def forward(self, x, augment=False, profile=False, visualize=False):# 是否在测试时也使用数据增强 Test Time Augmentation(TTA)if augment:return self._forward_augment(x)  # augmented inference, None  上下flip/左右flip# 默认执行,正常前向推理return self._forward_once(x, profile, visualize)  # single-scale inference, traindef _forward_augment(self, x):''' TTA Test Time Augmentation '''img_size = x.shape[-2:]  # height, widths = [1, 0.83, 0.67]  # scalesf = [None, 3, None]  # flips (2-ud上下, 3-lr左右)y = []  # outputsfor si, fi in zip(s, f):# scale_img缩放图片尺寸xi = scale_img(x.flip(fi) if fi else x, si, gs=int(self.stride.max()))yi = self._forward_once(xi)[0]  # forward# cv2.imwrite(f'img_{si}.jpg', 255 * xi[0].cpu().numpy().transpose((1, 2, 0))[:, :, ::-1])  # save# _descale_pred将推理结果恢复到相对原图图片尺寸yi = self._descale_pred(yi, fi, si, img_size)y.append(yi)y = self._clip_augmented(y)  # clip augmented tailsreturn torch.cat(y, 1), None  # augmented inference, traindef _descale_pred(self, p, flips, scale, img_size):# de-scale predictions following augmented inference (inverse operation)''' 用在上面的__init__函数上将推理结果恢复到原图图片尺寸上 TTA中用到:params p: 推理结果:params flips: 翻转标记(2-ud上下, 3-lr左右):params scale: 图片缩放比例:params img_size: 原图图片尺寸'''# 不同的方式前向推理使用公式不同,具体可看Detect函数if self.inplace:  # 默认执行True,不使用AWS Inferentiap[..., :4] /= scale  # de-scaleif flips == 2:p[..., 1] = img_size[0] - p[..., 1]  # de-flip udelif flips == 3:p[..., 0] = img_size[1] - p[..., 0]  # de-flip lrelse:x, y, wh = p[..., 0:1] / scale, p[..., 1:2] / scale, p[..., 2:4] / scale  # de-scaleif flips == 2:y = img_size[0] - y  # de-flip udelif flips == 3:x = img_size[1] - x  # de-flip lrp = torch.cat((x, y, wh, p[..., 4:]), -1)return pdef _clip_augmented(self, y):# Clip YOLOv5 augmented inference tailsnl = self.model[-1].nl  # number of detection layers (P3-P5)g = sum(4 ** x for x in range(nl))  # grid pointse = 1  # exclude layer counti = (y[0].shape[1] // g) * sum(4 ** x for x in range(e))  # indicesy[0] = y[0][:, :-i]  # largei = (y[-1].shape[1] // g) * sum(4 ** (nl - 1 - x) for x in range(e))  # indicesy[-1] = y[-1][:, i:]  # smallreturn ydef _initialize_biases(self, cf=None):  # initialize biases into Detect(), cf is class frequency''' 用在上面的__init__函数上 '''# https://arxiv.org/abs/1708.02002 section 3.3# cf = torch.bincount(torch.tensor(np.concatenate(dataset.labels, 0)[:, 0]).long(), minlength=nc) + 1.m = self.model[-1]  # Detect() modulefor mi, s in zip(m.m, m.stride):  # fromb = mi.bias.view(m.na, -1)  # conv.bias(255) to (3,85)b.data[:, 4] += math.log(8 / (640 / s) ** 2)  # obj (8 objects per 640 image)b.data[:, 5:5 + m.nc] += math.log(0.6 / (m.nc - 0.99999)) if cf is None else torch.log(cf / cf.sum())  # clsmi.bias = torch.nn.Parameter(b.view(-1), requires_grad=True)
Model = DetectionModel

6、文件修改

1、./models/common.py 增加C2模块

在这里插入图片描述

2、./models/yolo.py 在parse_model中增加C2

在这里插入图片描述
在这里插入图片描述

3、./models/yolov5s.yaml 在原第2层和原第3层之间插入C2模块

在这里插入图片描述

4、训练

python train.py --img 900 --batch 24 --epoch 100 --data data/ab.yaml --cfg models/yolov5s.yaml --weights yolov5s.pt

结果如下:
在这里插入图片描述


http://www.hkcw.cn/article/SJOotdiYeq.shtml

相关文章

无人机桥梁3D建模、巡检、检测的航线规划

无人机桥梁3D建模、巡检、检测的航线规划 无人机在3D建模、巡检和检测任务中的航线规划存在显著差异&#xff0c;主要体现在飞行高度、航线模式、精度要求和传感器配置等方面。以下是三者的详细对比分析&#xff1a; 1. 核心目标差异 任务类型主要目标典型应用场景3D建模 生成…

【FlashRAG】本地部署与demo运行(一)

FlashRAG 简介 FlashRAG 是一种高效检索增强生成&#xff08;Retrieval-Augmented Generation, RAG&#xff09;技术&#xff0c;旨在优化大规模语言模型&#xff08;LLMs&#xff09;的推理性能&#xff0c;尤其在处理长上下文或复杂查询时。其核心特点是结合了快速检索与动态…

低功耗架构突破:STM32H750 与 SD NAND (存储芯片)如何延长手环续航至 14 天

低功耗架构突破&#xff1a;STM32H750 与 SD NAND &#xff08;存储芯片&#xff09;如何延长手环续航至 14 天 卓越性能强化安全高效能效图形处理优势丰富集成特性 模拟模块实时监控保障数据完整性提升安全性与可靠性测量原理采样率相关结束语 在智能皮电手环及数据存储技术不…

MySQL之约束和表的增删查改

MySQL之约束和表的增删查改 一.数据库约束1.1数据库约束的概念1.2NOT NULL 非空约束1.3DEFAULT 默认约束1.4唯一约束1.5主键约束和自增约束1.6自增约束1.7外键约束1.8CHECK约束 二.表的增删查改2.1Create创建2.2Retrieve读取2.3Update更新2.4Delete删除和Truncate截断 一.数据库…

在线制作幼教早教行业自适应网站教程

你想知道怎么做自适应网站吗&#xff1f;今天就来教你在线用模板做个幼教早教行业的网站哦。 首先得了解啥是自适应网站。简单说呢&#xff0c;自适应网站就是能自动匹配不同终端设备的网站&#xff0c;像手机、平板、电脑等。那如何做幼早教自适应网站呢&#xff1f; 在乔拓云…

[特殊字符] 超强 Web React版 PDF 阅读器!支持分页、缩放、旋转、全屏、懒加载、缩略图!

在现代 Web 项目中&#xff0c;PDF 浏览是一个常见需求&#xff1a;从政务公文到合同协议&#xff0c;PDF 文件无处不在。但很多方案要么体验不佳&#xff0c;要么集成复杂。今天&#xff0c;我给大家带来一个开箱即用、功能全面的 PDF 预览组件 —— [PDFView](https://www.np…

裂缝仪在线监测装置:工程安全领域的“实时守卫者”

在基础设施运维领域&#xff0c;裂缝扩展是威胁建筑结构安全的核心隐患之一。传统人工巡检方式存在效率低、时效性差、数据主观性强等局限&#xff0c;而裂缝仪在线监测装置通过技术迭代&#xff0c;实现了对结构裂缝的自动化、持续性追踪&#xff0c;为工程安全评估提供科学依…

语音通信接通率、应答率和转化率有什么区别?

语音通信中的接通率、应答率和转化率是三个不同的关键指标&#xff0c;它们各自具有独特的定义和衡量标准&#xff0c;以下是它们之间的区别&#xff1a; 一、定义 1. 接通率&#xff1a; • 是指成功接通的电话数量占总拨打电话数量的百分比。具体来说&#xff0c;只要被叫响…

俄称击落千余架乌军无人机 乌称击退俄28次进攻

当地时间5月30日,俄罗斯国防部发布战报称,在过去一周里,俄军对乌境内的国防工业设施、军用机场基础设施、武器弹药储存设施等目标实施打击。俄军在苏梅、哈尔科夫、顿涅茨克等方向打退乌军多次进攻并发动攻势。俄防空部队击落乌军1439架固定翼无人机。此外,俄军控制了苏梅、…

阿富汗今年已有357人死于麻疹 大部分是儿童

据世界卫生组织报告显示,截至5月25日,阿富汗今年已记录了超过55000例麻疹疑似病例,其中已有357人死亡,死者大部分是儿童。当地医务系统专家认为,疫苗缺乏和营养不足是疾病快速传播的重要原因。目前阿富汗有1580万人吃不饱饭,大量儿童营养不良,难以抵御疾病侵袭,需要获得…

从双向奔赴到分道扬镳 “马特”组合缘何分手

当地时间5月30日,美国总统特朗普和美国企业家、政府效率部负责人埃隆马斯克在白宫举行新闻发布会。这是马斯克在政府效率部的最后一天。马斯克28日在社交媒体上说,他即将离开特朗普政府,不再继续担任“特别政府雇员”一职。这也意味着,马斯克在1月20日就任美国政府效率部负…

Form开发指南-第一弹:开发背景与基础环境

1 用户和常用工具 1.1 区分3类用户 OS用户&#xff1a;包括超级用户root&#xff0c;应用OS用户如applprod&#xff0c;数据库OS用户oraprod。数据库用户&#xff1a;包括内置管理用户sys、system&#xff0c;EBS用户apps&#xff0c;EBS各模块用户applys、gl、inv、po、ar、…

基于LBS的上门代厨APP开发全流程解析

上门做饭将会取代外卖行业成为新一轮的创业风口吗&#xff1f;杭州一位女士的3菜一汤88元套餐引爆社交网络&#xff0c;这个包含做饭、洗碗、收拾厨房的全套服务&#xff0c;正在重新定义"到家经济"的边界。当25岁的研究生系着围裙出现在客户厨房&#xff0c;当年轻姑…

Bootstrap项目 - 个人作品与成就展示网站

文章目录 前言一、项目整体概述1. 项目功能介绍1.1 导航栏1.2 首页模块1.3 关于我模块1.4 技能模块1.5 作品模块1.6 成就模块1.7 博客模块1.8 联系我模块 2. 技术选型说明 二、项目成果展示1. PC端展示1.1 首页1.2 关于我1.3 技能1.4 作品1.5 成就1.6 博客1.7 联系我 2. 移动端…

QML 滑动与翻转效果(Flickable与Flipable)

目录 引言相关阅读核心组件解析Flickable基础属性Flipable核心特性 示例解析示例1&#xff1a;可滑动列表&#xff08;FlickableDemo&#xff09;示例2&#xff1a;可翻转卡片&#xff08;FlipableCard&#xff09; 总结下载链接 引言 Qt Quick 框架提供的 Flickable 与 Flipa…

氮气吹扫电磁阀

一、氮气吹扫电磁阀的概述 氮气吹扫电磁阀是一种重要的工业自动控制设备&#xff0c;用于对工业设备中出现的杂质和沉淀物进行清理&#xff0c;以保证生产线的畅通和生产效率的稳定。其作用是在需要吹扫清洗的工业设备中&#xff0c;通过控制气源的气压&#xff0c;打开电磁阀…

【香港科大+华为诺亚方舟】Web Reconstruction方法:从原始网页文档合成高质量指令遵循数据,效果显著,代码开源

论文名称&#xff1a;Instruction-Tuning Data Synthesis from Scratch via Web Reconstruction 论文链接&#xff1a;https://arxiv.org/abs/2504.15573 机构&#xff1a;香港科技大学 华为诺亚方舟实验室 Github代码链接&#xff1a;https://github.com/YJiangcm/WebR 个人文…

星际巡航-第16届蓝桥第6次STEMA测评Scratch真题第4题

[导读]&#xff1a;超平老师的《Scratch蓝桥杯真题解析100讲》已经全部完成&#xff0c;后续会不定期解读蓝桥真题&#xff0c;这是Scratch蓝桥真题解析第233讲。 第16届蓝桥第6次STEMA测评已于2025年4月13日落下帷幕&#xff0c;编程题一共有5题&#xff08;初级组只有前4道编…

C++17新特性 类型推导

在传统C和C中&#xff0c;参数的类型都必须明确定义&#xff0c;这其实对我们快速进行编码没有任何帮助&#xff0c;尤 其是当我们面对一大堆复杂的模板类型时&#xff0c;必须明确的指出变量的类型才能进行后续的编码&#xff0c;这不仅拖 慢我们的开发效率&#xff0c;也让代…

leetcode 2359. 找到离给定两个节点最近的节点

给你一个 n 个节点的 有向图 &#xff0c;节点编号为 0 到 n - 1 &#xff0c;每个节点 至多 有一条出边。 有向图用大小为 n 下标从 0 开始的数组 edges 表示&#xff0c;表示节点 i 有一条有向边指向 edges[i] 。如果节点 i 没有出边&#xff0c;那么 edges[i] -1 。 同时…