我正在训练水果分类模型。截至目前,我的类(class)是: [“新鲜苹果”、“新鲜香蕉”、“新鲜橙子”]
我正在使用 ImageDataGenerator 和 flow_from_directory 来使用训练、验证和测试生成器。我已经训练了模型,现在想要将测试生成器输入到模型中以查看模型的性能。现在我的测试生成器中只有 2 个图像。我有以下代码来进行预测:
predictions = tuned_model.predict(test_generator)
score = tf.nn.softmax(predictions[0])
print(
'This image most likely belongs to {} with a {:.2f} percent
confidence.'.format(
class_names[np.argmax(score)], 100 * np.max(score)
)
)
结果如下:
This image most likely belongs to Fresh Apples with a 46.19 percent confidence.
是的,它的准确度很低,我只训练了 10 个周期,哈哈。但是,有没有办法可以看到正在测试哪个图像?或者知道这个预测是否正确的方法?
编辑:
包括生成器的代码...
generator = ImageDataGenerator(
rotation_range=45,
rescale=1./255,
horizontal_flip=True,
vertical_flip=True,
validation_split=.2
)
train_generator = generator.flow_from_directory(
train_path,
target_size=(im_height, im_width),
batch_size = batch_size,
subset='training'
)
validation_generator = generator.flow_from_directory(
train_path,
target_size=(im_height, im_width),
batch_size=batch_size,
subset='validation'
)
test_generator = generator.flow_from_directory(
test_path,
target_size= (im_height, im_width),
batch_size= batch_size,
)
就我的类标签而言,到目前为止我只是对它们进行了硬编码
class_names = ['Fresh Apples', 'Fresh Bananas', 'Fresh Bananas']
我知道我可能应该导入操作系统并根据文件结构创建标签,但除非绝对需要,否则我会稍后执行此操作。
最佳答案
我假设当您创建测试生成器时,您在 flow_from_directory 中设置了 shuffle=False 。然后使用
files=test_generator.filenames
class_dict=test_generator.class_indices # a dictionary of the form class name: class index
rev_dict={}
for key, value in class_dict.items()
rev_dict[value]=key # dictionary of the form class index: class name
files 是文件名列表,按照文件呈现预测的顺序排列。 然后做
predictions = tuned_model.predict(test_generator)
然后迭代预测
for i, p in enumerate(predictions)
index=np.argmax(p)
klass=rev_dict[index]
prob=p[index]
print('for file ', files[i], ' predicted class is ', klass,' with probability ',prob)
当然你也可以显示图像
关于tensorflow - 如何查看测试生成器中的图像以查看预测是否正确,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/69109151/