【已解决】YoloV5:AttributeError: Can‘t get attribute ‘C3‘ on <module ‘models.common‘ from

这是Yolov5的模块详细介绍,可以了解一下:https://blog.csdn.net/qq_41398619/article/details/127665092

学习替换yolo的主干网络:https://blog.csdn.net/qq_30017409/article/details/123300389

问题:在用yolov5自带的权重文件时出现了问题

原因:权重pt文件和新环境的YOLOv5的小版本不相同,导致无法使用。 网上的解决办法为:

方法一:在新的环境重新训练出权重文件即可成功运行。

方法二:将新的环境中的YOLOv5替换为当时训练权重文件时候的版本即可

但是不能成功解决。

解决方法:在common.py之中加入两个模块C3和SPPF

#在最上面需要引入warnings库
import warnings

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(C3, self).__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)  # act=FReLU(c2)
        self.m = nn.Sequential(*[Bottleneck(c_, c_, shortcut, g, e=1.0) for _ in range(n)])
        # self.m = nn.Sequential(*[CrossConv(c_, c_, 3, 1, g, 1.0, shortcut) for _ in range(n)])

    def forward(self, x):
        return self.cv3(torch.cat((self.m(self.cv1(x)), self.cv2(x)), dim=1))


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

猜你喜欢

转载自blog.csdn.net/qq_43681154/article/details/129651864
今日推荐