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

This is a detailed introduction to the module of Yolov5, you can find out: https://blog.csdn.net/qq_41398619/article/details/127665092

Learning to replace yolo's backbone network: https://blog.csdn.net/qq_30017409/article/details/123300389

Problem: There is a problem when using the weight file that comes with yolov5

Reason: The weight pt file is not the same as the small version of YOLOv5 in the new environment, which makes it unusable. The online solution is:

Method 1: Retrain the weight file in a new environment to run successfully.

Method 2: Replace YOLOv5 in the new environment with the version when training the weight file at that time

But can't resolve successfully.

Solution: Add two modules C3 and SPPF to common.py

#在最上面需要引入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))

Guess you like

Origin blog.csdn.net/qq_43681154/article/details/129651864