从 TensorFlow 2 ImageGenerator 获取预测标签

数据挖掘 机器学习 分类 喀拉斯 张量流 图像分类
2022-02-24 04:43:44

我创建了用于训练标记数据的图像生成器。现在我想使用生成器对未标记的数据进行预测。我创建了一个测试生成器,如下所示:

test_generator = gen_test.flow_from_directory(
                        test_path,
                        target_size=IMAGE_SIZE,
                        class_mode=None,
                        shuffle=False,
                        batch_size=batch_size)

我得到的输出似乎是一个像这样的热编码

array([[0., 0., 1., 0., 0.],
       [0., 0., 0., 0., 1.],
       [0., 0., 0., 0., 1.],
       ...,
       [0., 1., 0., 0., 0.],
       [0., 1., 0., 0., 0.],
       [0., 0., 0., 0., 1.]], dtype=float32)

我想知道为每个图像获取实际类标签的正确方法。例如,我的训练图像生成器中的类是这样的

array([0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 1, 1, 1, 1, 1, 1, 1, 1,
       1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1,
       1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1,
       1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1,
       1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1,
       1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 2, 2, 2, 2, 2, 2, 2, 2, 2,
       2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2,
       2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2,
       2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2,
       2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 3, 3, 3, 3, 3, 3, 4, 4, 4, 4, 4, 4,
       4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4,
       4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4,
       4, 4, 4, 4, 4, 4], dtype=int32)

我是第一次使用它,所以我可能有一种更简单的方法来获取这些信息。任何指针都非常感谢。

1个回答

使用argmaxwithmodel.predict是要走的路。

# testdata is the dataframe of Generator
paths = testdata.filenames # Your files path

y_pred = model.predict(testdata).argmax(axis=1) # Predict prob and get Class Indices
classes = testdata.class_indices  # Map of Indices to Class name

from keras.preprocessing import image
a_img_rand = np.random.randint(0,len(paths))   # A rand to pick a rand image
img = image.load_img(paths[a_img_rand])       
img = image.img_to_array(img)
from google.colab.patches import cv2_imshow
cv2_imshow(img)
print(f'Class Predicted ---- {list(classes)[y_pred[a_img_rand]]}')

在此处输入图像描述