给自己发发 学习一下哦 ,只会一点yolo 所以发

代码https://github.com/Oneflow-Inc/one-yolov5

教程也同样适用于ultralytics/yolov5因为one-yolov5仅仅是换了一个运行时后端而已,计算逻辑和代码相比于ultralytics/yolov5没有做任何改变。

YOLOv5针对不同大小(n, s, m, l, x)的网络整体架构都是一样的,只不过会在每个子模块中采用不同的深度和宽度,分别应对yaml文件中的depth_multiple和width_multiple参数。

还需要注意一点,官方除了n, s, m, l, x版本外还有n6, s6, m6, l6, x6,区别在于后者是针对更大分辨率的图片比如1280×1280,当然结构上也有些差异,前者只会下采样到32倍且采用3个预测特征层 , 而后者会下采样64倍,采用4个预测特征层。

本章将以 yolov5s为例,从配置文件models/yolov5s.yaml(https://github.com/Oneflow-Inc/one-yolov5/blob/main/models/yolov5s.yaml) 到 models/yolo.py(https://github.com/Oneflow-Inc/one-yolov5/blob/main/models/yolo.py) 源码进行解读。

yolov5s.yaml文件内容

nc:80#numberofclasses数据集中的类别数depth_multiple:0.33#modeldepthmultiple模型层数因子(用来调整网络的深度)width_multiple:0.50#layerchannelmultiple模型通道数因子(用来调整网络的宽度)#如何理解这个depth_multiple和width_multiple呢?它决定的是整个模型中的深度(层数)和宽度(通道数),具体怎么调整的结合后面的backbone代码解释。anchors:#表示作用于当前特征图的Anchor大小为xxx#9个anchor,其中P表示特征图的层级,P3/8该层特征图缩放为1/8,是第3层特征-[10,13,16,30,33,23]#P3/8,表示[10,13],[16,30],[33,23]3个anchor-[30,61,62,45,59,119]#P4/16-[116,90,156,198,373,326]#P5/32#YOLOv5sv6.0backbonebackbone:#[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,C3,[256]],[-1,1,Conv,[512,3,2]],#5-P4/16[-1,9,C3,[512]],[-1,1,Conv,[1024,3,2]],#7-P5/32[-1,3,C3,[1024]],[-1,1,SPPF,[1024,5]],#9]#YOLOv5sv6.0headhead:[[-1,1,Conv,[512,1,1]],[-1,1,nn.Upsample,[None,2,'nearest']],[[-1,6],1,Concat,[1]],#catbackboneP4[-1,3,C3,[512,False]],#13[-1,1,Conv,[256,1,1]],[-1,1,nn.Upsample,[None,2,'nearest']],[[-1,4],1,Concat,[1]],#catbackboneP3[-1,3,C3,[256,False]],#17(P3/8-small)[-1,1,Conv,[256,3,2]],[[-1,14],1,Concat,[1]],#catheadP4[-1,3,C3,[512,False]],#20(P4/16-medium)[-1,1,Conv,[512,3,2]],[[-1,10],1,Concat,[1]],#catheadP5[-1,3,C3,[1024,False]],#23(P5/32-large)[[17,20,23],1,Detect,[nc,anchors]],#Detect(P3,P4,P5)]

anchors 解读

yolov5 初始化了 9 个 anchors,分别在三个特征图 (feature map)中使用,每个 feature map 的每个 grid cell 都有三个 anchor 进行预测。分配规则:

  • 尺度越大的 feature map 越靠前,相对原图的下采样率越小,感受野越小,所以相对可以预测一些尺度比较小的物体(小目标),分配到的 anchors 越小。

  • 尺度越小的 feature map 越靠后,相对原图的下采样率越大,感受野越大,所以可以预测一些尺度比较大的物体(大目标),所以分配到的 anchors 越大。

  • 即在小特征图(feature map)上检测大目标,中等大小的特征图上检测中等目标,在大特征图上检测小目标。

backbone & head解读

[from, number, module, args] 参数

四个参数的意义分别是:

  • 第一个参数 from :从哪一层获得输入,-1表示从上一层获得,[-1, 6]表示从上层和第6层两层获得。

  • 第二个参数 number:表示有几个相同的模块,如果为9则表示有9个相同的模块。

  • 第三个参数 module:模块的名称,这些模块写在common.py中。

  • 第四个参数 args:类的初始化参数,用于解析作为 moudle 的传入参数。

下面以第一个模块Conv 为例介绍下common.py中的模块。

Conv 模块定义如下:

classConv(nn.Module):#Standardconvolutiondef__init__(self,c1,c2,k=1,s=1,p=None,g=1,act=True):#ch_in,ch_out,kernel,stride,padding,groups"""@Pargmc1:输入通道数@Pargmc2:输出通道数@Pargmk:卷积核大小(kernel_size)@Pargms:卷积步长(stride)@Pargmp:特征图填充宽度(padding)@Pargmg:控制分组,必须整除输入的通道数(保证输入的通道能被正确分组)"""super().__init__()#https://oneflow.readthedocs.io/en/master/generated/oneflow.nn.Conv2d.html?highlight=Convself.conv=nn.Conv2d(c1,c2,k,s,autopad(k,p),groups=g,bias=False)self.bn=nn.BatchNorm2d(c2)self.act=nn.SiLU()ifactisTrueelse(actifisinstance(act,nn.Module)elsenn.Identity())defforward(self,x):returnself.act(self.bn(self.conv(x)))defforward_fuse(self,x):returnself.act(self.conv(x))

比如上面把width_multiple设置为了0.5,那么第一个[64,6,2,2]就会被解析为[3,64*0.5=32,6,2,2],其中第一个3为输入channel(因为输入),32为输出channel。

关于调整网络大小的详解说明

yolo.py(https://github.com/Oneflow-Inc/one-yolov5/blob/main/models/yolo.py)的256行,有对yaml文件的nc,depth_multiple等参数读取,具体代码如下:

anchors,nc,gd,gw=d['anchors'],d['nc'],d['depth_multiple'],d['width_multiple']

“width_multiple”参数的作用前面介绍args参数中已经介绍过了,那么”depth_multiple”又是什么作用呢?

yolo.py(https://github.com/Oneflow-Inc/one-yolov5/blob/main/models/yolo.py)的257行有对参数的具体定义:

n=n_=max(round(n*gd),1)ifn>1elsen#depthgain暂且将这段代码当作公式(1)

其中gd 就是depth_multiple的值,n的值就是backbone中列表的第二个参数;

根据公示(1) 很容易看出 gd 影响 n 的大小,从而影响网络的结构大小。

后面各层之间的模块数量、卷积核大小和数量等也都产生了变化,YOLOv5l 与 YOLOv5s 相比较起来训练参数的大小成倍数增长,其模型的深度和宽度也会大很多,这就使得 YOLOv5l 的 精度值要比 YOLOv5s 好很多,因此在最终推理时的检测精度高,但是模型的推理速度更慢。

所以 YOLOv5 提供了不同的选择,如果想要追求推理速度可选用较小一些的模型如 YOLOv5s、YOLOv5m,如果想要追求精度更高对推理速度要求不高的可以选择其他两个稍大的模型。

如下面这张图:

yolov5模型复杂度比较图

Conv模块解读

网络结构预览

下面是根据yolov5s.yaml绘制的网络整体结构简化版。

yolov5s网络整体结构图

1.详细的网络结构图:https://oneflow-static.oss-cn-beijing.aliyuncs.com/one-yolo/imgs/yolov5s.onnx.png通过export.py导出的onnx格式,并通过https://netron.app/网站导出的图片(模型导出将在本教程的后续文章单独介绍)。 whaosoft aiothttp://143ai.com

2. 模块组件右边参数表示特征图的的形状,比如在第一层(Conv)输入图片形状为[3,640,640],关于这些参数,可以固定一张图片输入到网络并通过yolov5s.yaml的模型参数计算得到,并且可以在工程models/yolo.py通过代码进行print查看,详细数据可以参考附件表2.1。

yolo.py 解读

文件地址:https://github.com/Oneflow-Inc/one-yolov5/blob/main/models/yolo.py

文件主要包含三大部分:Detect类,Model类,和parse_model函数。

可以通过python models/yolo.py –cfg yolov5s.yaml运行该脚本进行观察。

parse_model函数解读

defparse_model(d,ch):#model_dict,input_channels(3)"""用在下面Model模块中解析模型文件(字典形式),并搭建网络结构这个函数其实主要做的就是:更新当前层的args(参数),计算c2(当前层的输出channel)=>使用当前层的参数搭建当前层=>生成layers+save@Paramsd:model_dict模型文件字典形式{dict:7}[yolov5s.yaml](https://github.com/Oneflow-Inc/one-yolov5/blob/main/models/yolov5s.yaml)中的6个元素+ch#Paramsch:记录模型每一层的输出channel初始ch=[3]后面会删除@returnnn.Sequential(*layers):网络的每一层的层结构@returnsorted(save):把所有层结构中from不是-1的值记下并排序[4,6,10,14,17,20,23]"""LOGGER.info(f"\n{'':>3}{'from':>18}{'n':>3}{'params':>10}{'module':<40}{'arguments':1elsen#depthgain#如果当前的模块m在本项目定义的模块类型中,就可以处理这个模块ifmin(Conv,GhostConv,Bottleneck,GhostBottleneck,SPP,SPPF,DWConv,MixConv2d,Focus,CrossConv,BottleneckCSP,C3,C3TR,C3SPP,C3Ghost,nn.ConvTranspose2d,DWConvTranspose2d,C3x):# c1:输入通道数 c2:输出通道数c1,c2=ch[f],args[0]#该层不是最后一层,则将通道数乘以宽度因子也就是说,宽度因子作用于除了最后一层之外的所有层ifc2!=no:#ifnotoutput# make_divisible的作用,使得原始的通道数乘以宽度因子之后取整到8的倍数,这样处理一般是让模型的并行性和推理性能更好。c2=make_divisible(c2*gw,8)#将前面的运算结果保存在args中,它也就是这个模块最终的输入参数。args=[c1,c2,*args[1:]]#根据每层网络参数的不同,分别处理参数具体各个类的参数是什么请参考它们的__init__方法这里不再详细解释了ifmin[BottleneckCSP,C3,C3TR,C3Ghost,C3x]:#这里的意思就是重复n次,比如conv这个模块重复n次,这个n是上面算出来的depthargs.insert(2,n)#numberofrepeatsn=1elifmisnn.BatchNorm2d:args=[ch[f]]elifmisConcat:c2=sum(ch[x]forxinf)elifmisDetect:args.append([ch[x]forxinf])ifisinstance(args[1],int):#numberofanchorsargs[1]=[list(range(args[1]*2))]*len(f)elifmisContract:c2=ch[f]*args[0]**2elifmisExpand:c2=ch[f]//args[0]**2else:c2=ch[f]#构建整个网络模块这里就是根据模块的重复次数n以及模块本身和它的参数来构建这个模块和参数对应的Modulem_=nn.Sequential(*(m(*args)for_inrange(n)))ifn>1elsem(*args)#module#获取模块(module type)具体名例如 models.common.Conv , models.common.C3 , models.common.SPPF 等。t=str(m)[8:-2].replace('__main__.','')# replace函数作用是字符串"__main__"替换为'',在当前项目没有用到这个替换。np=sum(x.numel()forxinm_.parameters())#numberparamsm_.i,m_.f,m_.type,m_.np=i,f,t,np#attachindex,'from'index,type,numberparamsLOGGER.info(f'{i:>3}{str(f):>18}{n_:>3}{np:10.0f}{t:<40}{str(args):<30}')#print"""如果x不是-1,则将其保存在save列表中,表示该层需要保存特征图。这里x%i与x等价例如在最后一层:f=[17,20,23],i=24y=[x%iforxin([f]ifisinstance(f,int)elsef)ifx!=-1]print(y)#[17,20,23]#写成x % i 可能因为:i - 1 =-1 % i (比如 f =[-1],则[x % i for x in f]代表[11])"""save.extend(x%iforxin([f]ifisinstance(f,int)elsef)ifx!=-1)#appendtosavelistlayers.append(m_)ifi==0:#如果是初次迭代,则新创建一个ch(因为形参ch在创建第一个网络模块时需要用到,所以创建网络模块之后再初始化ch)ch=[]ch.append(c2)#将所有的层封装为nn.Sequential,对保存的特征图排序returnnn.Sequential(*layers),sorted(save)

Model 类解读

classModel(nn.Module):#YOLOv5modeldef__init__(self,cfg='[yolov5s.yaml](https://github.com/Oneflow-Inc/one-yolov5/blob/main/models/yolov5s.yaml)',ch=3,nc=None,anchors=None):#model,inputchannels,numberofclassessuper().__init__()#如果cfg已经是字典,则直接赋值,否则先加载cfg路径的文件为字典并赋值给self.yaml。ifisinstance(cfg,dict):self.yaml=cfg#modeldictelse:#is*.yaml加载yaml模块importyaml#forflowhubself.yaml_file=Path(cfg).namewithopen(cfg,encoding='ascii',errors='ignore')asf:self.yaml=yaml.safe_load(f)#modeldict从yaml文件中加载出字典#Definemodel# ch:输入通道数。假如self.yaml有键‘ch’,则将该键对应的值赋给内部变量ch。假如没有‘ch’,则将形参ch赋给内部变量chch=self.yaml['ch']=self.yaml.get('ch',ch)#inputchannels#假如yaml中的nc和方法形参中的nc不一致,则覆盖yaml中的nc。ifncandnc!=self.yaml['nc']:LOGGER.info(f"Overridingmodel.yamlnc={self.yaml['nc']}withnc={nc}")self.yaml['nc']=nc#overrideyamlvalueifanchors:#anchors先验框的配置LOGGER.info(f'Overridingmodel.yamlanchorswithanchors={anchors}')self.yaml['anchors']=round(anchors)#overrideyamlvalue#得到模型,以及对应的保存的特征图列表。self.model,self.save=parse_model(deepcopy(self.yaml),ch=[ch])#model,savelistself.names=[str(i)foriinrange(self.yaml['nc'])]#defaultnames初始化类名列表,默认为[0,1,2...]#self.inplace=True默认True节省内存self.inplace=self.yaml.get('inplace',True)#Buildstrides,anchors确定步长、步长对应的锚框m=self.model[-1]#Detect()ifisinstance(m,Detect):#检验模型的最后一层是Detect模块s=256#2xminstridem.inplace=self.inplace#计算三个featuremap下采样的倍率[8,16,32]m.stride=flow.tensor([s/x.shape[-2]forxinself.forward(flow.zeros(1,ch,s,s))])#forward#检查anchor顺序与stride顺序是否一致anchor的顺序应该是从小到大,这里排一下序check_anchor_order(m)#mustbeinpixel-space(notgrid-space)#对应的anchor进行缩放操作,原因:得到anchor在实际的特征图中的位置,因为加载的原始anchor大小是相对于原图的像素,但是经过卷积池化之后,特征图的长宽变小了。m.anchors/=m.stride.view(-1,1,1)self.stride=m.strideself._initialize_biases()#onlyrunonce初始化偏置#Initweights,biases#调用oneflow_utils.py下initialize_weights初始化模型权重initialize_weights(self)self.info()#打印模型信息LOGGER.info('')#管理前向传播函数defforward(self,x,augment=False,profile=False,visualize=False):ifaugment:#是否在测试时也使用数据增强TestTimeAugmentation(TTA)returnself._forward_augment(x)#augmentedinference,Nonereturnself._forward_once(x,profile,visualize)#single-scaleinference,train#带数据增强的前向传播def_forward_augment(self,x):img_size=x.shape[-2:]#height,widths=[1,0.83,0.67]#scalesf=[None,3,None]#flips(2-ud,3-lr)y=[]#outputsforsi,fiinzip(s,f):xi=scale_img(x.flip(fi)iffielsex,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])#saveyi=self._descale_pred(yi,fi,si,img_size)y.append(yi)y=self._clip_augmented(y)#clipaugmentedtailsreturnflow.cat(y,1),None#augmentedinference,train#前向传播具体实现def_forward_once(self,x,profile=False,visualize=False):"""@paramsx:输入图像@paramsprofile:True可以做一些性能评估@paramsfeature_vis:True可以做一些特征可视化"""#y:存放着self.save=True的每一层的输出,因为后面的特征融合操作要用到这些特征图y,dt=[],[]#outputs#前向推理每一层结构m.i=indexm.f=fromm.type=类名m.np=numberofparamsforminself.model:#ifnotfrompreviouslayerm.f=当前层的输入来自哪一层的输出s的m.f都是-1ifm.f!=-1:#ifnotfrompreviouslayerx=y[m.f]ifisinstance(m.f,int)else[xifj==-1elsey[j]forjinm.f]#fromearlierlayersifprofile:self._profile_one_layer(m,x,dt)x=m(x)#runy.append(xifm.iinself.saveelseNone)#saveoutputifvisualize:feature_visualization(x,m.type,m.i,save_dir=visualize)returnx#将推理结果恢复到原图图片尺寸(逆操作)def_descale_pred(self,p,flips,scale,img_size):#de-scalepredictionsfollowingaugmentedinference(inverseoperation)"""用在上面的__init__函数上将推理结果恢复到原图图片尺寸TestTimeAugmentation(TTA)中用到de-scalepredictionsfollowingaugmentedinference(inverseoperation)@paramsp:推理结果@paramsflips:@paramsscale:@paramsimg_size:"""ifself.inplace:p[...,:4]/=scale#de-scaleifflips==2:p[...,1]=img_size[0]-p[...,1]#de-flipudelifflips==3:p[...,0]=img_size[1]-p[...,0]#de-fliplrelse:x,y,wh=p[...,0:1]/scale,p[...,1:2]/scale,p[...,2:4]/scale#de-scaleifflips==2:y=img_size[0]-y#de-flipudelifflips==3:x=img_size[1]-x#de-fliplrp=flow.cat((x,y,wh,p[...,4:]),-1)returnp#这个是TTA的时候对原图片进行裁剪,也是一种数据增强方式,用在TTA测试的时候。def_clip_augmented(self,y):#ClipYOLOv5augmentedinferencetailsnl=self.model[-1].nl#numberofdetectionlayers(P3-P5)g=sum(4**xforxinrange(nl))#gridpointse=1#excludelayercounti=(y[0].shape[1]//g)*sum(4**xforxinrange(e))#indicesy[0]=y[0][:,:-i]#largei=(y[-1].shape[1]//g)*sum(4**(nl-1-x)forxinrange(e))#indicesy[-1]=y[-1][:,i:]#smallreturny#打印日志信息前向推理时间def_profile_one_layer(self,m,x,dt):c=isinstance(m,Detect)#isfinallayer,copyinputasinplacefixo=thop.profile(m,inputs=(x.copy()ifcelsex,),verbose=False)[0]/1E9*2ifthopelse0#FLOPst=time_sync()for_inrange(10):m(x.copy()ifcelsex)dt.append((time_sync()-t)*100)ifm==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}')ifc:LOGGER.info(f"{sum(dt):10.2f}{'-':>10s}{'-':>10s}Total")#initializebiasesintoDetect(),cfisclassfrequencydef_initialize_biases(self,cf=None):#https://arxiv.org/abs/1708.02002section3.3#cf=flow.bincount(flow.tensor(np.concatenate(dataset.labels,0)[:,0]).long(),minlength=nc)+1.m=self.model[-1]#Detect()moduleformi,sinzip(m.m,m.stride):#fromb=mi.bias.view(m.na,-1).detach()#conv.bias(255)to(3,85)b[:,4]+=math.log(8/(640/s)**2)#obj(8objectsper640image)b[:,5:]+=math.log(0.6/(m.nc-0.999999))ifcfisNoneelseflow.log(cf/cf.sum())#clsmi.bias=flow.nn.Parameter(b.view(-1),requires_grad=True)#打印模型中最后Detect层的偏置biases信息(也可以任选哪些层biases信息)def_print_biases(self):"""打印模型中最后Detect模块里面的卷积层的偏置biases信息(也可以任选哪些层biases信息)"""m=self.model[-1]#Detect()moduleformiinm.m:#fromb=mi.bias.detach().view(m.na,-1).T#conv.bias(255)to(3,85)LOGGER.info(('%6gConv2d.bias:'+'%10.3g'*6)%(mi.weight.shape[1],*b[:5].mean(1).tolist(),b[5:].mean()))def_print_weights(self):"""打印模型中Bottleneck层的权重参数weights信息(也可以任选哪些层weights信息)"""forminself.model.modules():iftype(m)isBottleneck:LOGGER.info('%10.3g'%(m.w.detach().sigmoid()*2))#shortcutweights# fuse()是用来进行conv和bn层合并,为了提速模型推理速度。deffuse(self):#fusemodelConv2d()+BatchNorm2d()layers"""用在detect.py、val.pyfusemodelConv2d()+BatchNorm2d()layers调用oneflow_utils.py中的fuse_conv_and_bn函数和common.py中Conv模块的fuseforward函数"""LOGGER.info('Fusinglayers...')forminself.model.modules():#如果当前层是卷积层Conv且有bn结构,那么就调用fuse_conv_and_bn函数讲conv和bn进行融合,加速推理ifisinstance(m,(Conv,DWConv))andhasattr(m,'bn'):m.conv=fuse_conv_and_bn(m.conv,m.bn)#updateconvdelattr(m,'bn')#removebatchnorm移除bnremovebatchnormm.forward=m.forward_fuse#updateforward更新前向传播updateforward(反向传播不用管,因为这种推理只用在推理阶段)self.info()#打印conv+bn融合后的模型信息returnself#打印模型结构信息在当前类__init__函数结尾处有调用definfo(self,verbose=False,img_size=640):#printmodelinformationmodel_info(self,verbose,img_size)def_apply(self,fn):#Applyto(),cpu(),cuda(),half()tomodeltensorsthatarenotparametersorregisteredbuffersself=super()._apply(fn)m=self.model[-1]#Detect()ifisinstance(m,Detect):m.stride=fn(m.stride)m.grid=list(map(fn,m.grid))ifisinstance(m.anchor_grid,list):m.anchor_grid=list(map(fn,m.anchor_grid))returnself

Detect类解读

classDetect(nn.Module):"""Detect模块是用来构建Detect层的,将输入featuremap通过一个卷积操作和公式计算到我们想要的shape,为后面的计算损失或者NMS后处理作准备"""stride=None#stridescomputedduringbuildonnx_dynamic=False#ONNXexportparameterexport=False#exportmodedef__init__(self,nc=80,anchors=(),ch=(),inplace=True):#detectionlayersuper().__init__()#nc:分类数量self.nc=nc#numberofclasses#no:每个anchor的输出数self.no=nc+5#numberofoutputsperanchor#nl:预测层数,此次为3self.nl=len(anchors)#numberofdetectionlayers#na:anchors的数量,此次为3self.na=len(anchors[0])//2#numberofanchors#grid:格子坐标系,左上角为(1,1),右下角为(input.w/stride,input.h/stride)self.grid=[flow.zeros(1)]*self.nl#initgridself.anchor_grid=[flow.zeros(1)]*self.nl#initanchorgrid#写入缓存中,并命名为anchorsself.register_buffer('anchors',flow.tensor(anchors).float().view(self.nl,-1,2))#shape(nl,na,2)#将输出通过卷积到self.no*self.na的通道,达到全连接的作用self.m=nn.ModuleList(nn.Conv2d(x,self.no*self.na,1)forxinch)#outputconvself.inplace=inplace#useinplaceops(e.g.sliceassignment)defforward(self,x):z=[]#inferenceoutputforiinrange(self.nl):x[i]=self.m[i](x[i])#convbs,_,ny,nx=x[i].shape#x(bs,255,20,20)tox(bs,3,20,20,85)x[i]=x[i].view(bs,self.na,self.no,ny,nx).permute(0,1,3,4,2).contiguous()ifnotself.training:#inferenceifself.onnx_dynamicorself.grid[i].shape[2:4]!=x[i].shape[2:4]:#向前传播时需要将相对坐标转换到grid绝对坐标系中self.grid[i],self.anchor_grid[i]=self._make_grid(nx,ny,i)y=x[i].sigmoid()ifself.inplace:y[...,0:2]=(y[...,0:2]*2+self.grid[i])*self.stride[i]#xyy[...,2:4]=(y[...,2:4]*2)**2*self.anchor_grid[i]#whelse:#forYOLOv5onAWSInferentiahttps://github.com/ultralytics/yolov5/pull/2953xy,wh,conf=y.split((2,2,self.nc+1),4)#y.tensor_split((2,4,5),4)xy=(xy*2+self.grid[i])*self.stride[i]#xywh=(wh*2)**2*self.anchor_grid[i]#why=flow.cat((xy,wh,conf),4)z.append(y.view(bs,-1,self.no))returnxifself.trainingelse(flow.cat(z,1),)ifself.exportelse(flow.cat(z,1),x)#相对坐标转换到grid绝对坐标系def_make_grid(self,nx=20,ny=20,i=0):d=self.anchors[i].devicet=self.anchors[i].dtypeshape=1,self.na,ny,nx,2#gridshapey,x=flow.arange(ny,device=d,dtype=t),flow.arange(nx,device=d,dtype=t)yv,xv=flow.meshgrid(y,x,indexing="ij")grid=flow.stack((xv,yv),2).expand(shape)-0.5#addgridoffset,i.e.y=2.0*x-0.5anchor_grid=(self.anchors[i]*self.stride[i]).view((1,self.na,1,1,2)).expand(shape)returngrid,anchor_grid

附件

表2.1yolov5s.yaml解析表

层数formmouduleargumentsinputoutput
0-1Conv[3, 32, 6, 2, 2][3, 640, 640][32, 320, 320]
1-1Conv[32, 64, 3, 2][32, 320, 320][64, 160, 160]
2-1C3[64, 64, 1][64, 160, 160][64, 160, 160]
3-1Conv[64, 128, 3, 2][64, 160, 160][128, 80, 80]
4-1C3[128, 128, 2][128, 80, 80][128, 80, 80]
5-1Conv[128, 256, 3, 2][128, 80, 80][256, 40, 40]
6-1C3[256, 256, 3][256, 40, 40][256, 40, 40]
7-1Conv[256, 512, 3, 2][256, 40, 40][512, 20, 20]
8-1C3[512, 512, 1][512, 20, 20][512, 20, 20]
9-1SPPF[512, 512, 5][512, 20, 20][512, 20, 20]
10-1Conv[512, 256, 1, 1][512, 20, 20][256, 20, 20]
11-1Upsample[None, 2, ‘nearest’][256, 20, 20][256, 40, 40]
12[-1, 6]Concat[1][1, 256, 40, 40],[1, 256, 40, 40][512, 40, 40]
13-1C3[512, 256, 1, False][512, 40, 40][256, 40, 40]
14-1Conv[256, 128, 1, 1][256, 40, 40][128, 40, 40]
15-1Upsample[None, 2, ‘nearest’][128, 40, 40][128, 80, 80]
16[-1, 4]Concat[1][1, 128, 80, 80],[1, 128, 80, 80][256, 80, 80]
17-1C3[256, 128, 1, False][256, 80, 80][128, 80, 80]
18-1Conv[128, 128, 3, 2][128, 80, 80][128, 40, 40]
19[-1, 14]Concat[1][1, 128, 40, 40],[1, 128, 40, 40][256, 40, 40]
20-1C3[256, 256, 1, False][256, 40, 40][256, 40, 40]
21-1Conv[256, 256, 3, 2][256, 40, 40][256, 20, 20]
22[-1, 10]Concat[1][1, 256, 20, 20],[1, 256, 20, 20][512, 20, 20]
23-1C3[512, 512, 1, False][512, 20, 20][512, 20, 20]
24[17, 20, 23]Detect[80, [[10, 13, 16, 30, 33, 23], [30, 61, 62, 45, 59, 119], [116, 90, 156, 198, 373, 326]], [128, 256, 512]][1, 128, 80, 80],[1, 256, 40, 40],[1, 512, 20, 20][1, 3, 80, 80, 85],[1, 3, 40, 40, 85],[1, 3, 20, 20, 85]