YOLOv5代码详解(common.py部分)

4. common.py

该部分是backbone各个模块参数讲解。

4.1 卷积层

4.1.1 深度分离卷积层

深度分离(DepthWise)卷积层,是GCONV的极端情况,分组数量等于输入通道数量,即每个通道作为一个小组分别进行卷积,结果联结作为输出,Cin = Cout = g,没有bias项。参考链接
在这里插入图片描述

def DWConv(c1, c2, k=1, s=1, act=True):
    # Depthwise convolution
    return Conv(c1, c2, k, s, g=math.gcd(c1, c2), act=act)

k=1是卷积核kenel,s=1是步长stride,math.gcd() 返回的是最大公约数。

4.1.1 标准卷积层

class Conv(nn.Module):
    # Standard convolution
    def __init__(self, c1, c2, k=1, s=1, g=1, act=True):  # ch_in, ch_out, kernel, stride, groups
        super(Conv, self).__init__()
        self.conv = nn.Conv2d(c1, c2, k, s, autopad(k, p), groups=g, bias=False)
        self.bn = nn.BatchNorm2d(c2)
        self.act = nn.LeakyReLU(0.1, inplace=True) if act else nn.Identity()

    def forward(self, x):  # 前向计算
        return self.act(self.bn(self.conv(x)))

    def fuseforward(self, x):  # 前向融合计算
        return self.act(self.conv(x))
  • g=1表示从输入通道到输出通道的阻塞连接数为1。
  • autopad(k, p)此处换成自动填充。
  • 标准卷积层包括conv+BN+Leaky relu。
    在这里插入图片描述

nn.Conv2d函数基本参数是:
nn.Conv2d(self, in_channels, out_channels, kernel_size, stride=1, padding=0, dilation=1, groups=1, bias=True, padding_mode='zeros')

参数:nn.Conv参考链接

  • in_channel:输入数据的通道数,例RGB图片通道数为3。
  • out_channel: 输出数据的通道数,这个根据模型调整。
  • kennel_size: 卷积核大小,可以是int,或tuple;kennel_size=2,意味着卷积大小(2,2),kennel_size=(2,3),意味着卷积大小(2,3)即非正方形卷积。
  • stride:步长,默认为1,与kennel_size类似,stride=2,意味着步长上下左右扫描皆为2,stride=(2,3),左右扫描步长为2,上下为3。
  • padding:零填充。
  • groups:从输入通道到输出通道的阻塞连接数。
  • bias:如果为“True“,则向输出添加可学习的偏置。

4.2 标准Bottleneck

class Bottleneck(nn.Module):
    # Standard bottleneck
    def __init__(self, c1, c2, shortcut=True, g=1, e=0.5):  # ch_in, ch_out, shortcut, groups, expansion
        super(Bottleneck, self).__init__()
        c_ = int(c2 * e)  # hidden channels
        self.cv1 = Conv(c1, c_, 1, 1)
        self.cv2 = Conv(c_, c2, 3, 1, g=g)
        self.add = shortcut and c1 == c2

    def forward(self, x):
        return x + self.cv2(self.cv1(x)) if self.add else self.cv2(self.cv1(x))

在这里插入图片描述

4.3 BottleneckCSP

这部分是几个标准Bottleneck的堆叠+几个标准卷积层。

class BottleneckCSP(nn.Module):
    # CSP Bottleneck https://github.com/WongKinYiu/CrossStagePartialNetworks
    def __init__(self, c1, c2, n=1, shortcut=True, g=1, e=0.5):  # ch_in, ch_out, number, shortcut, groups, expansion
        super(BottleneckCSP, self).__init__()
        c_ = int(c2 * e)  # hidden channels
        self.cv1 = Conv(c1, c_, 1, 1)
        self.cv2 = nn.Conv2d(c1, c_, 1, 1, bias=False)
        self.cv3 = nn.Conv2d(c_, c_, 1, 1, bias=False)
        self.cv4 = Conv(2 * c_, c2, 1, 1)
        self.bn = nn.BatchNorm2d(2 * c_)  # applied to cat(cv2, cv3)
        self.act = nn.LeakyReLU(0.1, inplace=True)
        self.m = nn.Sequential(*[Bottleneck(c_, c_, shortcut, g, e=1.0) for _ in range(n)])

    def forward(self, x):
        y1 = self.cv3(self.m(self.cv1(x)))
        y2 = self.cv2(x)
        return self.cv4(self.act(self.bn(torch.cat((y1, y2), dim=1))))

4.4 SPP

SPP是空间金字塔池化的缩写。

class SPP(nn.Module):
    # Spatial pyramid pooling layer used in YOLOv3-SPP
    def __init__(self, c1, c2, k=(5, 9, 13)):
        super(SPP, self).__init__()
        c_ = c1 // 2  # hidden channels
        self.cv1 = Conv(c1, c_, 1, 1)
        self.cv2 = Conv(c_ * (len(k) + 1), c2, 1, 1)
        self.m = nn.ModuleList([nn.MaxPool2d(kernel_size=x, stride=1, padding=x // 2) for x in k])

    def forward(self, x):
        x = self.cv1(x)
        return self.cv2(torch.cat([x] + [m(x) for m in self.m], 1))

torch.cat() 是将两个tensor横着拼接在一起。
补充:或者是list列表中的tensor。参考链接

4.5 Flatten

在全局平均池化以后使用,去掉2个维度。

class Flatten(nn.Module):
    # Use after nn.AdaptiveAvgPool2d(1) to remove last 2 dimensions
    def forward(self, x):
        return x.view(x.size(0), -1)

x.size(0)是batch的大小。

4.6 Focus

把宽度w和高度h的信息整合到c空间中。

class Focus(nn.Module):
    # Focus wh information into c-space
    def __init__(self, c1, c2, k=1, s=1, p=None, g=1, act=True):  # ch_in, ch_out, kernel, stride, padding, groups
        super(Focus, self).__init__()
        self.conv = Conv(c1 * 4, c2, k, s, p, g, act)

    def forward(self, x):  # x(b,c,w,h) -> y(b,4c,w/2,h/2)
        return self.conv(torch.cat([x[..., ::2, ::2], x[..., 1::2, ::2], x[..., ::2, 1::2], x[..., 1::2, 1::2]], 1))

需要注意的是,concat的获取如下图所示。图参考链接
在这里插入图片描述

4.7 Concat

拼接函数,将两个tensor进行拼接起来。

class Concat(nn.Module):
    # Concatenate a list of tensors along dimension
    def __init__(self, dimension=1):
        super(Concat, self).__init__()
        self.d = dimension

    def forward(self, x):
        return torch.cat(x, self.d)

觉得好的话,记得给个赞哦~
有什么错误,请在评论区指出。转载请注明出处,谢谢啦!

  • 31
    点赞
  • 230
    收藏
    觉得还不错? 一键收藏
  • 19
    评论
yolov5是一个目标检测算法,yolo.py是其中的一个核心文件,主要实现了模型的构建和训练。下面是yolo.py代码详解: 1. 导入必要的库和模块 ```python import torch import torch.nn as nn import numpy as np from collections import OrderedDict from utils.general import anchors, autopad, scale_img, check_anchor_order, check_file, check_img_size, \ check_requirements, non_max_suppression, xyxy2xywh, xywh2xyxy, plot_one_box from utils.torch_utils import time_synchronized, fuse_conv_and_bn, model_info from models.common import Conv, DWConv ``` 2. 定义YOLOv5模型 ```python class YOLOv5(nn.Module): def __init__(self, nc=80, anchors=(), ch=(), inference=False): # model, input channels, number of classes super(YOLOv5, self).__init__() self.nc = nc # number of classes self.no = nc + 5 # number of outputs per anchor self.nl = len(anchors) # number of detection layers self.na = len(anchors[0]) // 2 # number of anchors per layer self.grid = [torch.zeros(1)] * self.nl # init grid a = torch.tensor(anchors).float().view(self.nl, -1, 2) self.register_buffer('anchors', a) # shape(nl,na,2) self.register_buffer('anchor_grid', a.clone().view(self.nl, 1, -1, 1, 1, 2)) # shape(nl,1,na,1,1,2) self.m = nn.ModuleList(nn.Conv2d(x, self.no * self.na, 1) for x in ch) # output conv self.inference = inference # inference flag ``` 3. 定义前向传播函数 ```python def forward(self, x): self.img_size = x.shape[-2:] # store image size x = self.forward_backbone(x) # backbone z = [] # inference output for i in range(self.nl): x[i] = self.m[i](x[i]) # conv bs, _, ny, nx = x[i].shape # x(bs,255,20,20) to x(bs,3,20,20,85) x[i] = x[i].view(bs, self.na, self.no, ny, nx).permute(0, 1, 3, 4, 2).contiguous() if not self.training: # inference if self.inference == 'tflite': z.append(x[i].detach().cpu()) # inference tflite else: io = x[i].sigmoid() io[..., 4:] = io[..., 4:] * io[..., 4:].mean(1, keepdim=True) * self.nc # sigmoid obj,class scores bxy = io[..., :2].sigmoid() * 2. - 0.5 + self.grid[i] # xy bwh = io[..., 2:4].exp() * self.anchor_grid[i] # wh xywh = torch.cat((bxy, bwh), -1).view(bs, -1, 4) * self.stride[i] # xywh (center+offset) relative to image size z.append(xywh.view(bs, -1, self.no), ) # xywhn return x if self.training else (torch.cat(z, 1), x) ``` 4. 定义后向传播函数 ```python def forward_backbone(self, x): x = self.conv1(x) x = self.bn1(x) x = self.act1(x) x = self.pool1(x) x = self.layer1(x) x = self.layer2(x) x = self.layer3(x) x = self.layer4(x) x = self.layer5(x) x = self.layer6(x) x = self.layer7(x) x = self.layer8(x) x = self.layer9(x) return x ``` 以上就是yolo.py代码详解,其中包括了YOLOv5模型的定义和前向传播函数的实现。相关问题如下: 相关问题: 1. YOLOv5模型的输入和输出是什么? 2. YOLOv5模型的训练过程是怎样的? 3. YOLOv5模型中的anchors是什么?

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 19
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值