如何获取PyTorch CachedImageFolder数据集中的类别标签字符串
要得到类别标签的字符串而不是索引,你可以在构建数据集时使用target_transform参数来进行转换。你可以创建一个字典来将索引映射到类别标签的字符串,然后使用target_transform函数来将索引转换为字符串。\n\n以下是一个示例代码:\n\npython\nclass CachedImageFolder(DatasetFolder):\n def __getitem__(self, index):\n ""\"\n Args:\n index (int): Index\n Returns:\n tuple: (image, target) where target is class_index of the target class.\n ""\"\n path, target = self.samples[index]\n image = self.loader(path)\n if self.transform is not None:\n img = self.transform(image)\n else:\n img = image\n if self.target_transform is not None:\n target = self.target_transform(target)\n\n return img, target\n\ndef build_dataset(split, config):\n # 创建类别标签的字符串映射\n label_map = {\n 0: 'class_0',\n 1: 'class_1',\n 2: 'class_2',\n 3: 'class_3',\n 4: 'class_4'\n }\n \n # 创建转换函数,将索引转换为类别标签的字符串\n def target_transform(target):\n return label_map[target]\n \n # 构建数据集,并传入转换函数\n dataset = CachedImageFolder(root, transform=transform, target_transform=target_transform)\n return dataset, nb_classes\n\ndataset_val, _ = build_dataset('val', config=config)\n\n\n现在,dataset_val.classes将返回类别标签的字符串列表,而不是索引列表。
原文地址: https://www.cveoy.top/t/topic/pn9E 著作权归作者所有。请勿转载和采集!