yolov5_6.0以上的模型和6.0以下的模型不兼容问题。Can‘t get attribute ‘SPPF‘

yolov5_6.0以上的模型和6.0以下的模型不兼容问题:

[完全解决yolov5权重6.0与之前版本不兼容问题]Can‘t get attribute ‘SPPF‘ on emodule ‘models.common‘

项目场景:

例如:不论train 还是pridect 还是load(model)新旧模型各种不兼容


正常描述

6.0以下小版本可以运行 ,如下:

D:\ProgramData\Miniconda3\python.exe D:/yolov5-6.0/ai2/compare.py

Fusing layers... 
{'辣椒炒蛋': '0.9343', '蒜苔炒肉': '0.8900', '肉沫酸豆角': '0.7458', '干煸青豆': '0.7290', '凉面': '0.7008'}
 model with cuda local Runtime: 0.302 seconds per image, FPS: 3.31

Process finished with exit code 0

问题描述一:“SPPF”

6.0以上版本出现的问题 ,如下:
![在这里插入图片描述](https://img-blog.csdnimg.cn/c3b17147772b4bb89eb9878119a1b9ac.jpegyolov5_6.0以上的模型和6.0以下的模型不兼容问题。Can‘t get attribute ‘SPPF‘_第1张图片

原因分析:

提示:说是没有sppf这个方法:


解决方案:

在老版本的 common.py 文件里 添加如下代码:

import warnings
class SPPF(nn.Module):
    # Spatial Pyramid Pooling - Fast (SPPF) layer for YOLOv5 by Glenn Jocher
    def __init__(self, c1, c2, k=5):  # equivalent to SPP(k=(5, 9, 13))
        super().__init__()
        c_ = c1 // 2  # hidden channels
        self.cv1 = Conv(c1, c_, 1, 1)
        self.cv2 = Conv(c_ * 4, c2, 1, 1)
        self.m = nn.MaxPool2d(kernel_size=k, stride=1, padding=k // 2)

    def forward(self, x):
        x = self.cv1(x)
        with warnings.catch_warnings():
            warnings.simplefilter('ignore')  # suppress torch 1.9.0 max_pool2d() warning
            y1 = self.m(x)
            y2 = self.m(y1)
            return self.cv2(torch.cat((x, y1, y2, self.m(y2)), 1))

问题描述二:“RuntimeError”

6.0以上版本出现的问题 ,如下:
![在这里插入图片描述](https://img-blog.csdnimg.cn/c3b17147772b4bb89eb9878119a1b9ac.jpegyolov5_6.0以上的模型和6.0以下的模型不兼容问题。Can‘t get attribute ‘SPPF‘_第2张图片

原因分析:

提示:大家都说通道channel不相同,但是我觉得说的不是我这个问题,我现在加载模型,怎么调整channel:


解决方案:

在老版本的 common.py 文件里老代码 替换掉

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))

问题描述三:“RuntimeError”

6.0以上版本出现的问题 ,如下:
yolov5_6.0以上的模型和6.0以下的模型不兼容问题。Can‘t get attribute ‘SPPF‘_第3张图片

原因分析:

提示:没查是啥意思,反正这里面这几个地方有问题,对应改:


解决方案:

在老版本的 yolo.py 文件里老代码class Detect(nn.Module): class Detect(nn.Module): 替换掉
写法如下:
后面有一句话这里,原代码有个check_version(torch.__version__,'1.10.0'): 的方法:这个方法不存在,目的是为了版本大于1.10,所以换个写法就ok了。
if (torch.__version__>='1.10.0'): # torch>=1.10.0 meshgrid workaround for torch>=0.7 compatibility

class Detect(nn.Module):
    stride = None  # strides computed during build
    onnx_dynamic = False  # ONNX export parameter
    export = False  # export mode

    def __init__(self, nc=80, anchors=(), ch=(), inplace=True):  # detection layer
        super().__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
        self.grid = [torch.zeros(1)] * self.nl  # init grid
        self.anchor_grid = [torch.zeros(1)] * self.nl  # init anchor grid
        self.register_buffer('anchors', torch.tensor(anchors).float().view(self.nl, -1, 2))  # shape(nl,na,2)
        self.m = nn.ModuleList(nn.Conv2d(x, self.no * self.na, 1) for x in ch)  # output conv
        self.inplace = inplace  # use inplace ops (e.g. slice assignment)

    def forward(self, x):
        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.onnx_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)

                y = x[i].sigmoid()
                if self.inplace:
                    y[..., 0:2] = (y[..., 0:2] * 2 + self.grid[i]) * self.stride[i]  # xy
                    y[..., 2:4] = (y[..., 2:4] * 2) ** 2 * self.anchor_grid[i]  # wh
                else:  # for YOLOv5 on AWS Inferentia https://github.com/ultralytics/yolov5/pull/2953
                    xy, wh, conf = y.split((2, 2, self.nc + 1), 4)  # y.tensor_split((2, 4, 5), 4)  # torch 1.8.0
                    xy = (xy * 2 + self.grid[i]) * self.stride[i]  # xy
                    wh = (wh * 2) ** 2 * self.anchor_grid[i]  # wh
                    y = torch.cat((xy, wh, conf), 4)
                z.append(y.view(bs, -1, 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):
        d = self.anchors[i].device
        t = self.anchors[i].dtype
        shape = 1, self.na, ny, nx, 2  # grid shape
        y, x = torch.arange(ny, device=d, dtype=t), torch.arange(nx, device=d, dtype=t)
        if (torch.__version__>='1.10.0'):  # torch>=1.10.0 meshgrid workaround for torch>=0.7 compatibility
            # yv, xv = torch.meshgrid(y, x, indexing='ij')
            yv, xv = torch.meshgrid(y, x)
        else:
            yv, xv = torch.meshgrid(y, x)
        grid = torch.stack((xv, yv), 2).expand(shape) - 0.5  # add grid offset, i.e. y = 2.0 * x - 0.5
        anchor_grid = (self.anchors[i] * self.stride[i]).view((1, self.na, 1, 1, 2)).expand(shape)
        return grid, anchor_grid

剩下的就是顺利的拿到结果了,祝大家一切顺利:
如果还有其他问题 可以留言,大家一起探讨!!!

你可能感兴趣的:(YOLOv5,目标检测,模型)