如何使用 Tensorflow/Keras 找到正确预测的测试集图像

How to find correctly predicted test set images by using Tensorflow/Keras

如何找到正确预测的测试集图像? (比如将这些图像存储到 folder/or 中,知道它们的文件名)在此先感谢。 :)

我正在使用 ImageDataGenerator 作为测试数据集,代码是:

image = ImageDataGenerator(rotation_range=15,
                           width_shift_range=0.05,
                           height_shift_range=0.05,
                           rescale=1/255,
                           shear_range=0.05,
                           zoom_range=0.05,
                           horizontal_flip=True,
                           fill_mode='nearest'
                           )
test_image = image.flow_from_directory(test_path,
                                       target_size=image_shape[:2],
                                       color_mode='grayscale',
                                       batch_size=20,
                                       class_mode='binary', 
                                       shuffle=False)

您可以使用生成器的一些属性

filenames= test_image.filename # is an ordered list of the files as produced by the generator
labels=test_image.labels # is an ordered list of the labels for each file
class_dict=test_image.class_indices # is a dictionary of the form {classname: class index}

我通常反转 class_dict 所以 class 索引是键,class 名称是值。代码是

for key,value in class_dict.items():
        new_dict[value]=key    # dictionary {integer of class number: string of class name}
    
classes=list(new_dict.values())  # is a list of class names in order

请注意,只有在 flow_from_directory 中设置 shuffle=False 时,呈现给 model.fit 的文件的顺序才与文件名和标签的顺序相同。这是将生成器提交给 model.predict 时的常见做法。