使用 Keras 对多 class 图像 class 化进行多重预测

Multiple predictions of multi-class image classification with Keras

我在 Keras 中用文件夹中的图像训练了一个 CNN(两种蜜蜂)。我有第二个文件夹,其中包含未标记的 bees 个用于预测的图像。

我能够预测单个图像(按照下面的代码)。

from keras.preprocessing import image

test_image = image.load_img('data/test/20300.jpg')
test_image = image.img_to_array(test_image)
test_image = np.expand_dims(test_image, axis = 0)

prob = classifier.predict_proba(test_image)

结果:

prob
Out[214]: array([[1., 0.]], dtype=float32)

我希望能够预测所有图像(大约 300 张)。

有没有办法批量加载和预测所有图像? predict() 是否能够如预期和数组预测那样处理它?

Model.predict_proba()(实际上是 predict())接受批量输入。来自文档:

Generates class probability predictions for the input samples. The input samples are processed batch by batch.

您只需要加载多个图像并将它们粘合在一个 numpy 数组中。通过扩展 0 维,您的代码已经在 test_image 中使用了一批 1。要完成图片,还有一个 Model.predict_on_batch() 方法。

要加载一批测试图像,您可以使用image.list_picturesImageDataGenerator.flow_from_directory()(与Model.predict_generator()方法兼容,请参阅documentation中的示例)。