解决 Python ImagenetDataset 类 KeyError: 'assembly_line' 错误
解决 Python ImagenetDataset 类 KeyError: 'assembly_line' 错误
你的代码片段中出现的 KeyError: 'assembly_line' 错误表明在 sense_to_name 字典中没有找到名为 'assembly_line' 的键。
错误原因分析:
这个错误通常出现在以下两种情况:
- 字典中缺少键: 你的
sense_to_name字典中确实没有 'assembly_line' 键的定义,导致在使用sense_to_name['assembly_line']时无法找到对应值。 - 文件路径错误: 你可能将
assembly_line文件夹放在了错误的路径下,导致在读取文件时找不到该文件夹。
解决方法:
-
检查字典:
- 确保
sense_to_name字典中包含 'assembly_line' 键。 - 检查
sense数据结构,确保 'assembly_line' 对应的id值在sense_to_name中被正确映射。
- 确保
-
检查文件路径:
- 确认
assembly_line文件夹是否存在于path指定的路径下。 - 仔细检查文件路径的写法,避免拼写错误或路径错误。
- 确认
代码示例:
class ImagenetDataset(Dataset):
def __init__(self, path, transform=None):
self.transform = transform
self.paths = []
self.labels = []
self.label_to_idx = defaultdict(int)
self.idx_to_label = []
self.idx_to_text = []
sense_to_name = {}
i = 0
for item in sense:
sense_num = 'n' + sense[item]['id'].split('-')[0]
sense_to_name[sense_num] = imagenet_classes[i]
i += 1
for directory in os.listdir(path):
First = True
f = os.path.join(path, directory)
if os.path.isdir(f):
for image in os.listdir(f):
ext = image.split('.')[-1]
if ext == 'jpg':
image_path = os.path.join(f, image)
self.paths.append(image_path)
# 确保 'assembly_line' 存在于 sense_to_name 字典中
if directory in sense_to_name:
label_name = sense_to_name[directory]
if First:
First = False
self.label_to_idx[directory] = len(self.idx_to_label)
self.idx_to_label.append(directory)
self.idx_to_text.append(label_name)
self.labels.append(self.label_to_idx[directory])
else:
print(f'Warning: Key {directory} not found in sense_to_name dictionary.')
代码解释:
- 代码添加了一个
if directory in sense_to_name:语句,用于判断directory是否存在于sense_to_name字典中。 - 如果
directory不存在,则会打印一条警告信息,避免程序崩溃。
注意:
- 如果你确定
sense_to_name字典中应该包含 'assembly_line' 键,请检查你的代码逻辑和sense数据结构,确保 'assembly_line' 的id值被正确映射到sense_to_name中。 - 如果你确定 'assembly_line' 文件夹存在于正确的路径下,请检查文件路径的写法,避免拼写错误或路径错误。
通过以上方法,你可以有效地解决 KeyError: 'assembly_line' 错误,并确保你的代码正常运行。
原文地址: https://www.cveoy.top/t/topic/igz1 著作权归作者所有。请勿转载和采集!