tensorflow - 如何查看测试生成器中的图像以查看预测是否正确

标签 tensorflow keras conv-neural-network image-classification

我正在训练水果分类模型。截至目前,我的类(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/

相关文章:

python - 如何将 TensorFlow 2D 卷积 (tf.nn.conv2d) 应用于单个(非批量)2D 图像?

python - 具有矢量输出和 2D 图像图输入的 CNN(输入是数组)

python - Actor-Critic 模型永远不会收敛

python - TF中的Keras,如何在不执行梯度下降的情况下获得每个示例的损失值?

tensorflow - 从零开始训练 Resnet 深度神经网络

python - 如何控制使用 tfrecords 和 steps_per_epoch 读取哪些样本

python - 即使我使用相同的层模块构建完全相同的模型,Tensorflow 和 Keras 显示的结果略有不同

python - 如何安装 plaidML/plaidML-keras

python - 从卷积网络中删除顺序后,我得到 : "TypeError: ' Tensor' object is not callable"

python - 如何在图像上方剪切空白