Daniel Vargas
Daniel Vargas

Reputation: 1040

Multiple predictions of multi-class image classification with Keras

I trained a CNN in Keras with images in a folder (two types of bees). I have a second folder with unlabeled bees images for prediction.

I'm able to predict a single image (as per below code).

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)

Result:

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

I would like to be able to predict all of the images (around 300).

Is there a way to load and predict all the images in a batch? And will predict() be able to handle it, as it expects and array to predict?

Upvotes: 2

Views: 2020

Answers (1)

Maxim
Maxim

Reputation: 53778

Model.predict_proba() (which is a synonym of predict() really) accepts the batch input. From the documentation:

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

You just need to load several images and glue them together in a single numpy array. By expanding the 0 dimension your code already uses a batch of 1 in test_image. To complete the picture there's also a Model.predict_on_batch() method.

To load a batch of test images you can use image.list_pictures or ImageDataGenerator.flow_from_directory() (which is compatible with Model.predict_generator() method, see the examples in the documentation).

Upvotes: 1

Related Questions