当前位置:   article > 正文

【YOLOv5】使用yolov5训练模型时报错合集_yolov5分布式训练报错

yolov5分布式训练报错


前言

这篇文章用来记录在使用yolov5训练模型时报错处理,持续更新······

2024/4/18
【问题一】VsCode终端无法进入Anaconda创建的虚拟环境
【问题二】怎么在VsCode中为项目配置Anaconda创建的虚拟环境
【问题三】yolov5训练模型时报错RuntimeError: result type Float can’t be cast to the desired output type __int64
【问题四】 yolov5训练模型时出现警告AttributeError: ‘FreeTypeFont’ object has no attribute ‘getsize’

2024/4/19
【问题五】yolov5加载模型时报错AttributeError: module numpy has no attribute int

2024/4/27
【问题六】yolov5训练模型时报错Can‘t get attribute ‘DetectionModel‘ on <module ‘models.yolo‘ from


问题1 – VsCode终端无法进入Anaconda创建的虚拟环境

【问题描述】

在这里插入图片描述

【问题分析】

VsCode新建终端默认是powershell,需把VsCode终端默认为cmd。

【解决方式】

方法一

在这里插入图片描述

方法二
  • 1、左下角选择设置
    在这里插入图片描述
    2、在搜索框中输入powershell选择Command Prompt
    在这里插入图片描述
  • 3、重启VsCode

问题2 – 怎么在VsCode中为项目配置Anaconda创建的虚拟环境

【问题描述】

假设我们在Anaconda Prompt下创建了一个虚拟环境,我们想要在VsCode中导入创建好的虚拟环境。

【解决方式】

  • 1、在代码空白处同时按下 Ctrl + Shift + P
  • 2、在弹出的搜索框输入“选择解释器”
    在这里插入图片描述
  • 3、点击进入Python: 选择解释器
  • 4、选择你想要的环境
    在这里插入图片描述
  • 5、右下角查看项目的环境
    在这里插入图片描述

问题3 – yolov5训练模型时报错RuntimeError: result type Float can’t be cast to the desired output type __int64

【问题描述】

报错信息如下:
在这里插入图片描述

【问题分析】

PyTorch 的早期版本中,当进行某些运算时,PyTorch 可能会自动对张量的数据类型进行调整以适应操作的需求。然而,在新版本的PyTorch 中,这种自动转换可能不再发生,因此需要显式地进行数据类型的转换。
通过添加 .long() 方法到 torch.ones创建的张量上,可以明确地将该张量的数据类型从默认的浮点数(float)转换为长整型(long)。

【解决方式】

  • 1、找到 loss.py 文件
  • 2、修改loss.py
    将 loss.py 文件中的第173行代码
    gain = torch.ones(7, device=targets.device) # normalized to gridspace gain
    改为
    gain = torch.ones(7, device=targets.device).long()
    在这里插入图片描述
  • 3、按Ctrl + S键对代码进行保存

问题4 – yolov5训练模型时出现警告AttributeError: ‘FreeTypeFont’ object has no attribute ‘getsize’

【问题描述】

报错信息如下:
在这里插入图片描述

【问题分析】

问题出在库Pillow中的getsize函数,getsize已弃用,已在Pillow 10(2023-07-01)中删除。

【解决方式】

方法一

1、找到 plots.py 文件
2、在 plots.py 中添加以下代码

import PIL
def check_version(target_version):
    """
    Check if the current PIL version is greater than or equal to the target version.

    Args:
        target_version (str): The target version string to compare against (e.g., '9.2.0').

    Returns:
        bool: True if the current PIL version is greater than or equal to the target version, False otherwise.
    """
    current_version = PIL.__version__
    current_version_parts = [int(part) for part in current_version.split('.')]
    target_version_parts = [int(part) for part in target_version.split('.')]

    # Compare version parts
    for cur, tgt in zip(current_version_parts, target_version_parts):
        if cur > tgt:
            return True
        elif cur < tgt:
            return False

    # If all parts are equal, the versions are equal or current version is shorter
    return True
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14
  • 15
  • 16
  • 17
  • 18
  • 19
  • 20
  • 21
  • 22
  • 23
  • 24

在这里插入图片描述

3、修改Annotator类的__init__方法
在__init__方法中添加以下代码段:

if check_version('9.2.0'):
    self.font.getsize = lambda x: self.font.getbbox(x)[2:4]  # text width, height
  • 1
  • 2

在这里插入图片描述

4、按Ctrl + S键对代码进行保存

方法二

1、打开Anaconda Prompt

2、进入你为yolov5项目配置的虚拟环境

conda activate yolo_v5
  • 1

将“yolo_v5”改为你自己创建的虚拟环境名

3、输入以下命令查看安装的pillow版本

pip show pillow
  • 1

4、使用以下命令卸载pillow

pip uninstall pillow
  • 1

5、安装版本为9.5.0的pillow(有挂代理/梯子记得关掉)

pip install pillow==9.5
  • 1

如果安装失败或下载速度慢,可改用国内源进行安装,如换清华源:

pip install pillow==9.5 -i https://mirrors.tuna.tsinghua.edu.cn/pypi/web/simple --trusted-host=https://mirrors.tuna.tsinghua.edu.cn/pypi/web/simple
  • 1

问题5 – yolov5训练模型时报错AttributeError: module numpy has no attribute int

【问题分析】

这是由于从NumPy 1.x系列开始,numpy.int、numpy.intc、numpy.intp和numpy.int8等类型别名已经被弃用,并在后续版本中被移除。如果你使用了这些版本可能会报错:AttributeError: module numpy has no attribute int 。

【解决方式】

  • 1、在 utils 文件夹下找到 datasets.py和general.py文件
  • 2、在datasets.py中,分别将第445行、第474行、第845行代码中的 np.int 改为 int
  • 3、在general.py中,将第470行代码中的 np.int 改为 int

问题6 – yolov5训练模型时报错Can‘t get attribute ‘DetectionModel‘ on <module ‘models.yolo‘ from

【问题分析】

使用的模型版本不匹配导致。

【解决方式】

1、找到models文件夹下的yolo.py文件,将以下三个类( class Segment(Detect)、class BaseModel(nn.Module)、class DetectionModel(BaseModel) )的内容全部复制进去。

class Segment(Detect):
    # YOLOv5 Segment head for segmentation models
    def __init__(self, nc=80, anchors=(), nm=32, npr=256, ch=(), inplace=True):
        """Initializes YOLOv5 Segment head with options for mask count, protos, and channel adjustments."""
        super().__init__(nc, anchors, ch, inplace)
        self.nm = nm  # number of masks
        self.npr = npr  # number of protos
        self.no = 5 + nc + self.nm  # number of outputs per anchor
        self.m = nn.ModuleList(nn.Conv2d(x, self.no * self.na, 1) for x in ch)  # output conv
        self.proto = Proto(ch[0], self.npr, self.nm)  # protos
        self.detect = Detect.forward

    def forward(self, x):
        """Processes input through the network, returning detections and prototypes; adjusts output based on
        training/export mode.
        """
        p = self.proto(x[0])
        x = self.detect(self, x)
        return (x, p) if self.training else (x[0], p) if self.export else (x[0], p, x[1])
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14
  • 15
  • 16
  • 17
  • 18
  • 19
class BaseModel(nn.Module):
    """YOLOv5 base model."""

    def forward(self, x, profile=False, visualize=False):
        """Executes a single-scale inference or training pass on the YOLOv5 base model, with options for profiling and
        visualization.
        """
        return self._forward_once(x, profile, visualize)  # single-scale inference, train

    def _forward_once(self, x, profile=False, visualize=False):
        """Performs a forward pass on the YOLOv5 model, enabling profiling and feature visualization options."""
        y, dt = [], []  # outputs
        for m in self.model:
            if m.f != -1:  # if not from previous layer
                x = y[m.f] if isinstance(m.f, int) else [x if j == -1 else y[j] for j in m.f]  # from earlier layers
            if profile:
                self._profile_one_layer(m, x, dt)
            x = m(x)  # run
            y.append(x if m.i in self.save else None)  # save output
            if visualize:
                feature_visualization(x, m.type, m.i, save_dir=visualize)
        return x

    def _profile_one_layer(self, m, x, dt):
        """Profiles a single layer's performance by computing GFLOPs, execution time, and parameters."""
        c = m == self.model[-1]  # is final layer, copy input as inplace fix
        o = thop.profile(m, inputs=(x.copy() if c else x,), verbose=False)[0] / 1e9 * 2 if thop else 0  # FLOPs
        t = time_sync()
        for _ in range(10):
            m(x.copy() if c else x)
        dt.append((time_sync() - t) * 100)
        if m == 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}")
        if c:
            LOGGER.info(f"{sum(dt):10.2f} {'-':>10s} {'-':>10s}  Total")

    def fuse(self):
        """Fuses Conv2d() and BatchNorm2d() layers in the model to improve inference speed."""
        LOGGER.info("Fusing layers... ")
        for m in self.model.modules():
            if isinstance(m, (Conv, DWConv)) and hasattr(m, "bn"):
                m.conv = fuse_conv_and_bn(m.conv, m.bn)  # update conv
                delattr(m, "bn")  # remove batchnorm
                m.forward = m.forward_fuse  # update forward
        self.info()
        return self

    def info(self, verbose=False, img_size=640):
        """Prints model information given verbosity and image size, e.g., `info(verbose=True, img_size=640)`."""
        model_info(self, verbose, img_size)

    def _apply(self, fn):
        """Applies transformations like to(), cpu(), cuda(), half() to model tensors excluding parameters or registered
        buffers.
        """
        self = super()._apply(fn)
        m = self.model[-1]  # Detect()
        if isinstance(m, (Detect, Segment)):
            m.stride = fn(m.stride)
            m.grid = list(map(fn, m.grid))
            if isinstance(m.anchor_grid, list):
                m.anchor_grid = list(map(fn, m.anchor_grid))
        return self

  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14
  • 15
  • 16
  • 17
  • 18
  • 19
  • 20
  • 21
  • 22
  • 23
  • 24
  • 25
  • 26
  • 27
  • 28
  • 29
  • 30
  • 31
  • 32
  • 33
  • 34
  • 35
  • 36
  • 37
  • 38
  • 39
  • 40
  • 41
  • 42
  • 43
  • 44
  • 45
  • 46
  • 47
  • 48
  • 49
  • 50
  • 51
  • 52
  • 53
  • 54
  • 55
  • 56
  • 57
  • 58
  • 59
  • 60
  • 61
  • 62
  • 63
  • 64
  • 65
class DetectionModel(BaseModel):
    # YOLOv5 detection model
    def __init__(self, cfg="yolov5s.yaml", ch=3, nc=None, anchors=None):
        """Initializes YOLOv5 model with configuration file, input channels, number of classes, and custom anchors."""
        super().__init__()
        if isinstance(cfg, dict):
            self.yaml = cfg  # model dict
        else:  # is *.yaml
            import yaml  # for torch hub

            self.yaml_file = Path(cfg).name
            with open(cfg, encoding="ascii", errors="ignore") as f:
                self.yaml = yaml.safe_load(f)  # model dict

        # Define model
        ch = self.yaml["ch"] = self.yaml.get("ch", ch)  # input channels
        if nc and nc != self.yaml["nc"]:
            LOGGER.info(f"Overriding model.yaml nc={self.yaml['nc']} with nc={nc}")
            self.yaml["nc"] = nc  # override yaml value
        if anchors:
            LOGGER.info(f"Overriding model.yaml anchors with anchors={anchors}")
            self.yaml["anchors"] = round(anchors)  # override yaml value
        self.model, self.save = parse_model(deepcopy(self.yaml), ch=[ch])  # model, savelist
        self.names = [str(i) for i in range(self.yaml["nc"])]  # default names
        self.inplace = self.yaml.get("inplace", True)

        # Build strides, anchors
        m = self.model[-1]  # Detect()
        if isinstance(m, (Detect, Segment)):
            s = 256  # 2x min stride
            m.inplace = self.inplace
            forward = lambda x: self.forward(x)[0] if isinstance(m, Segment) else self.forward(x)
            m.stride = torch.tensor([s / x.shape[-2] for x in forward(torch.zeros(1, ch, s, s))])  # forward
            check_anchor_order(m)
            m.anchors /= m.stride.view(-1, 1, 1)
            self.stride = m.stride
            self._initialize_biases()  # only run once

        # Init weights, biases
        initialize_weights(self)
        self.info()
        LOGGER.info("")

    def forward(self, x, augment=False, profile=False, visualize=False):
        """Performs single-scale or augmented inference and may include profiling or visualization."""
        if augment:
            return self._forward_augment(x)  # augmented inference, None
        return self._forward_once(x, profile, visualize)  # single-scale inference, train

    def _forward_augment(self, x):
        """Performs augmented inference across different scales and flips, returning combined detections."""
        img_size = x.shape[-2:]  # height, width
        s = [1, 0.83, 0.67]  # scales
        f = [None, 3, None]  # flips (2-ud, 3-lr)
        y = []  # outputs
        for si, fi in zip(s, f):
            xi = scale_img(x.flip(fi) if fi else x, 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])  # save
            yi = self._descale_pred(yi, fi, si, img_size)
            y.append(yi)
        y = self._clip_augmented(y)  # clip augmented tails
        return torch.cat(y, 1), None  # augmented inference, train

    def _descale_pred(self, p, flips, scale, img_size):
        """De-scales predictions from augmented inference, adjusting for flips and image size."""
        if self.inplace:
            p[..., :4] /= scale  # de-scale
            if flips == 2:
                p[..., 1] = img_size[0] - p[..., 1]  # de-flip ud
            elif flips == 3:
                p[..., 0] = img_size[1] - p[..., 0]  # de-flip lr
        else:
            x, y, wh = p[..., 0:1] / scale, p[..., 1:2] / scale, p[..., 2:4] / scale  # de-scale
            if flips == 2:
                y = img_size[0] - y  # de-flip ud
            elif flips == 3:
                x = img_size[1] - x  # de-flip lr
            p = torch.cat((x, y, wh, p[..., 4:]), -1)
        return p

    def _clip_augmented(self, y):
        """Clips augmented inference tails for YOLOv5 models, affecting first and last tensors based on grid points and
        layer counts.
        """
        nl = self.model[-1].nl  # number of detection layers (P3-P5)
        g = sum(4**x for x in range(nl))  # grid points
        e = 1  # exclude layer count
        i = (y[0].shape[1] // g) * sum(4**x for x in range(e))  # indices
        y[0] = y[0][:, :-i]  # large
        i = (y[-1].shape[1] // g) * sum(4 ** (nl - 1 - x) for x in range(e))  # indices
        y[-1] = y[-1][:, i:]  # small
        return y

    def _initialize_biases(self, cf=None):
        """
        Initializes biases for YOLOv5's Detect() module, optionally using class frequencies (cf).

        For details see https://arxiv.org/abs/1708.02002 section 3.3.
        """
        # cf = torch.bincount(torch.tensor(np.concatenate(dataset.labels, 0)[:, 0]).long(), minlength=nc) + 1.
        m = self.model[-1]  # Detect() module
        for mi, s in zip(m.m, m.stride):  # from
            b = mi.bias.view(m.na, -1)  # conv.bias(255) to (3,85)
            b.data[:, 4] += math.log(8 / (640 / s) ** 2)  # obj (8 objects per 640 image)
            b.data[:, 5 : 5 + m.nc] += (
                math.log(0.6 / (m.nc - 0.99999)) if cf is None else torch.log(cf / cf.sum())
            )  # cls
            mi.bias = torch.nn.Parameter(b.view(-1), requires_grad=True)
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14
  • 15
  • 16
  • 17
  • 18
  • 19
  • 20
  • 21
  • 22
  • 23
  • 24
  • 25
  • 26
  • 27
  • 28
  • 29
  • 30
  • 31
  • 32
  • 33
  • 34
  • 35
  • 36
  • 37
  • 38
  • 39
  • 40
  • 41
  • 42
  • 43
  • 44
  • 45
  • 46
  • 47
  • 48
  • 49
  • 50
  • 51
  • 52
  • 53
  • 54
  • 55
  • 56
  • 57
  • 58
  • 59
  • 60
  • 61
  • 62
  • 63
  • 64
  • 65
  • 66
  • 67
  • 68
  • 69
  • 70
  • 71
  • 72
  • 73
  • 74
  • 75
  • 76
  • 77
  • 78
  • 79
  • 80
  • 81
  • 82
  • 83
  • 84
  • 85
  • 86
  • 87
  • 88
  • 89
  • 90
  • 91
  • 92
  • 93
  • 94
  • 95
  • 96
  • 97
  • 98
  • 99
  • 100
  • 101
  • 102
  • 103
  • 104
  • 105
  • 106
  • 107
  • 108
  • 109

2、找到models文件夹下的common.py文件,将以下类( class Proto(nn.Module) )的内容复制进去。

class Proto(nn.Module):
    # YOLOv5 mask Proto module for segmentation models
    def __init__(self, c1, c_=256, c2=32):
        """Initializes YOLOv5 Proto module for segmentation with input, proto, and mask channels configuration."""
        super().__init__()
        self.cv1 = Conv(c1, c_, k=3)
        self.upsample = nn.Upsample(scale_factor=2, mode="nearest")
        self.cv2 = Conv(c_, c_, k=3)
        self.cv3 = Conv(c_, c2)

    def forward(self, x):
        """Performs a forward pass using convolutional layers and upsampling on input tensor `x`."""
        return self.cv3(self.cv2(self.upsample(self.cv1(x))))
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
声明:本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有侵权的内容,请联系我们。转载请注明出处:【wpsshop博客】
推荐阅读
相关标签
  

闽ICP备14008679号