yolov8 No labels found in /path/train.cache解决

在用yolov8中ultralytics/datasets/coco.yaml训练时出现了no labels found in train2017.cache的错误。

model.train(
        data="ultralytics/datasets/coco.yaml",
        epochs=100,
        imgsz=640,
        batch=16,
        save_period=10,
    )

下面查找一个这个问题出现的原因。

这里并没有提前下载coco数据集,是在训练时自动下载的,下载速度比较慢。
然后会在datasets下面出现一个coco文件夹(如果文件夹没有出现在这里,请查看~/.config/Ultralytics/settings.yaml中的路径设置).

yolov8 No labels found in /path/train.cache解决_第1张图片

train.cache在labels文件夹里。它并不是下载的,而是根据images里的train和val图片找到labels里面对应的文件之后生成的。
所以要查看在这个生成的过程中出了什么问题。

首先查看images和labels的路径是否正确。
ultralytics/yolo/data/dataset.py中查看label_files,看文件是否存在。
(网上很多文章中这一步已经能解决问题)

    def get_labels(self):
        """Returns dictionary of labels for YOLO training."""
        self.label_files = img2label_paths(self.im_files)
        #print(self.label_files)
        cache_path = Path(self.label_files[0]).parent.with_suffix('.cache')

这一步博主查看文件夹是存在这些文件的。还需要继续找原因。
报错的地方在这里。

        # Display cache
        nf, nm, ne, nc, n = cache.pop('results')  # found, missing, empty, corrupt, total
        if exists and LOCAL_RANK in (-1, 0):
            d = f'Scanning {cache_path}... {nf} images, {nm + ne} backgrounds, {nc} corrupt'
            tqdm(None, desc=self.prefix + d, total=n, initial=n, bar_format=TQDM_BAR_FORMAT)  # display cache results
            if cache['msgs']:
                LOGGER.info('\n'.join(cache['msgs']))  # display warnings
        if nf == 0:  # number of labels found
            raise FileNotFoundError(f'{self.prefix}No labels found in {cache_path}, can not start training. {HELP_URL}')

显然出现了nf=0. nf为什么会为0呢。很可能是cache在生成过程中出了问题,下面要找到cache生成的代码。
还是在dataset.py
nf在这里+1操作,很显然哪里出了问题才没有进行+1操作。

    def cache_labels(self, path=Path('./labels.cache')):
        """Cache dataset labels, check images and read shapes.
        Args:
            path (Path): path where to save the cache file (default: Path('./labels.cache')).
        Returns:
            (dict): labels.
        """
        x = {'labels': []}
        nm, nf, ne, nc, msgs = 0, 0, 0, 0, []  # number missing, found, empty, corrupt, messages
        desc = f'{self.prefix}Scanning {path.parent / path.stem}...'
        total = len(self.im_files)
        nkpt, ndim = self.data.get('kpt_shape', (0, 0))
        if self.use_keypoints and (nkpt <= 0 or ndim not in (2, 3)):
            raise ValueError("'kpt_shape' in data.yaml missing or incorrect. Should be a list with [number of "
                             "keypoints, number of dims (2 for x,y or 3 for x,y,visible)], i.e. 'kpt_shape: [17, 3]'")
        with ThreadPool(NUM_THREADS) as pool:
            results = pool.imap(func=verify_image_label,
                                iterable=zip(self.im_files, self.label_files, repeat(self.prefix),
                                             repeat(self.use_keypoints), repeat(len(self.data['names'])), repeat(nkpt),
                                             repeat(ndim)))
            pbar = tqdm(results, desc=desc, total=total, bar_format=TQDM_BAR_FORMAT)
            for im_file, lb, shape, segments, keypoint, nm_f, nf_f, ne_f, nc_f, msg in pbar:
                nm += nm_f
                nf += nf_f
                ne += ne_f
                nc += nc_f
                if im_file:
                    x['labels'].append(
                        dict(
                            im_file=im_file,
                            shape=shape,
                            cls=lb[:, 0:1],  # n, 1
                            bboxes=lb[:, 1:],  # n, 4
                            segments=segments,
                            keypoints=keypoint,
                            normalized=True,
                            bbox_format='xywh'))
                if msg:
                    msgs.append(msg)
                pbar.desc = f'{desc} {nf} images, {nm + ne} backgrounds, {nc} corrupt'
            pbar.close()

在这里发现找不到trains文件夹里面的图片,
ultralytics/datasets/coco/images/train2017文件夹查看,发现文件夹为空。
再看train2017.zip的大小只有2.2kB! 下载失败了。
问题竟然出在没有确认下载的文件是否已损坏。

你可能感兴趣的:(DeepLearning,YOLO,人工智能)