You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

使用ImageDataGenerator测试时如何查看对应测试图像判断预测是否正确

前置错误修正

首先先修正两个影响结果的明显问题:

  1. 硬编码的类别标签错误,第三个类别应为Fresh Oranges,同时建议和生成器的class_indices对齐,避免顺序错配:
# 可以直接通过生成器获取标签顺序,不用硬编码
class_names = list(test_generator.class_indices.keys())
# 手动修正的话写为:class_names = ['Fresh Apples', 'Fresh Bananas', 'Fresh Oranges']
  1. 测试集不应该使用训练用的数据增强(旋转、翻转等),且必须关闭shuffle才能让预测结果和图像文件顺序匹配。

查看测试图像与对应预测结果的实现方法

步骤1:重新定义测试生成器

单独定义测试专用的生成器,仅做归一化,关闭shuffle:

# 测试集仅做归一化,不应用数据增强
test_datagen = ImageDataGenerator(rescale=1./255)
test_generator = test_datagen.flow_from_directory(
    test_path,
    target_size=(im_height, im_width),
    batch_size=batch_size,
    shuffle=False # 关键参数:保证预测顺序和文件顺序一致
)

步骤2:批量预测并关联文件信息

flow_from_directory生成的对象内置filenames(所有测试文件的相对路径)、labels(所有测试文件的真实标签索引)属性,可以直接和预测结果一一对应:

import matplotlib.pyplot as plt
import numpy as np
import tensorflow as tf

# 全量预测所有测试样本
predictions = tuned_model.predict(test_generator)
scores = tf.nn.softmax(predictions, axis=1)

# 遍历输出所有样本的对应信息
for idx in range(len(test_generator.filenames)):
    # 获取文件信息与真实标签
    img_file = test_generator.filenames[idx]
    true_label = class_names[test_generator.labels[idx]]
    # 获取预测信息
    pred_idx = np.argmax(scores[idx])
    pred_label = class_names[pred_idx]
    pred_conf = 100 * np.max(scores[idx])
    
    print(f"测试样本{idx+1}")
    print(f"对应文件:{img_file}")
    print(f"真实类别:{true_label}")
    print(f"预测类别:{pred_label} | 置信度:{pred_conf:.2f}%")
    print("-"*40)

# 可视化指定索引的图像(比如你之前打印的第一个样本,索引为0)
# 读取测试集图像批次
test_imgs, _ = next(test_generator)
plt.imshow(test_imgs[0])
plt.title(f"真实类别:{class_names[test_generator.labels[0]]}\n预测类别:{class_names[np.argmax(scores[0])]} {np.max(scores[0])*100:.2f}%")
plt.axis('off')
plt.show()

额外优化建议

你当前预测置信度低除了训练轮次少之外,测试集应用数据增强也是核心原因之一,修改测试生成器后预测精度会有明显提升。如果需要更准确的评估,建议固定训练时的随机种子,避免每次训练结果波动过大。

内容的提问来源于stack exchange,提问作者LeGOATJames23

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.10.05 01:15:03