根据报错信息,是因为数据集中缺少一个文件导致的错误。需要检查数据集的完整性。如果数据集确实存在缺失文件,可以尝试从数据集中删除这个文件或者将其修复。

修改方法:检查数据集中是否存在缺失文件,如果存在缺失文件,可以尝试从数据集中删除这个文件或者将其修复。

修改代码:

import os
from PIL import Image
import numpy as np

class CatDogDataset(paddle.io.Dataset):
    def __init__(self, data_dir, mode='train', transform=None):
        super(CatDogDataset, self).__init__()
        self.data_dir = data_dir
        self.mode = mode
        self.transform = transform
        self.img_paths = []

        if mode == 'train':
            self.data_dir = os.path.join(self.data_dir, 'cat_12_train')
        elif mode == 'test':
            self.data_dir = os.path.join(self.data_dir, 'cat_12_test')
        else:
            raise ValueError("mode should be 'train' or 'test', but got {}.".format(mode))

        self.img_paths = [os.path.join(self.data_dir, x) for x in os.listdir(self.data_dir)]
        
    def __getitem__(self, idx):
        img_path = self.img_paths[idx]
        img = Image.open(img_path).convert('RGB')
        
        if self.transform is not None:
            img = self.transform(img)
            
        if self.mode == 'test':
            return img
        
        if 'cat' in img_path:
            label = np.array([1], dtype=np.float32)
        elif 'dog' in img_path:
            label = np.array([0], dtype=np.float32)
        else:
            raise ValueError("Invalid image path: {}".format(img_path))
        
        return img, label
    
    def __len__(self):
        return len(self.img_paths)

在读取图片时,添加了异常处理代码,以便能够检测到缺失文件的情况,并及时报错。同时,如果缺失文件的数量不是很多,可以考虑将缺失文件从数据集中删除,以免影响模型的训练效果

Exception in thread Thread-6 _thread_loopTraceback most recent call last File optcondalibpython310threadingpy line 1016 in _bootstrap_inner selfrun File optcondalibpython310threadingpy line 953 i

原文地址: https://www.cveoy.top/t/topic/hbTd 著作权归作者所有。请勿转载和采集!

免费AI点我,无需注册和登录