How to predict input image using trained model in Keras? How to predict input image using trained model in Keras? python python

How to predict input image using trained model in Keras?


If someone is still struggling to make predictions on images, here is the optimized code to load the saved model and make predictions:

# Modify 'test1.jpg' and 'test2.jpg' to the images you want to predict onfrom keras.models import load_modelfrom keras.preprocessing import imageimport numpy as np# dimensions of our imagesimg_width, img_height = 320, 240# load the model we savedmodel = load_model('model.h5')model.compile(loss='binary_crossentropy',              optimizer='rmsprop',              metrics=['accuracy'])# predicting imagesimg = image.load_img('test1.jpg', target_size=(img_width, img_height))x = image.img_to_array(img)x = np.expand_dims(x, axis=0)images = np.vstack([x])classes = model.predict_classes(images, batch_size=10)print classes# predicting multiple images at onceimg = image.load_img('test2.jpg', target_size=(img_width, img_height))y = image.img_to_array(img)y = np.expand_dims(y, axis=0)# pass the list of multiple images np.vstack()images = np.vstack([x, y])classes = model.predict_classes(images, batch_size=10)# print the classes, the images belong toprint classesprint classes[0]print classes[0][0]


You can use model.predict() to predict the class of a single image as follows [doc]:

# load_model_sample.pyfrom keras.models import load_modelfrom keras.preprocessing import imageimport matplotlib.pyplot as pltimport numpy as npimport osdef load_image(img_path, show=False):    img = image.load_img(img_path, target_size=(150, 150))    img_tensor = image.img_to_array(img)                    # (height, width, channels)    img_tensor = np.expand_dims(img_tensor, axis=0)         # (1, height, width, channels), add a dimension because the model expects this shape: (batch_size, height, width, channels)    img_tensor /= 255.                                      # imshow expects values in the range [0, 1]    if show:        plt.imshow(img_tensor[0])                                   plt.axis('off')        plt.show()    return img_tensorif __name__ == "__main__":    # load model    model = load_model("model_aug.h5")    # image path    img_path = '/media/data/dogscats/test1/3867.jpg'    # dog    #img_path = '/media/data/dogscats/test1/19.jpg'      # cat    # load a single image    new_image = load_image(img_path)    # check prediction    pred = model.predict(new_image)

In this example, a image is loaded as a numpy array with shape (1, height, width, channels). Then, we load it into the model and predict its class, returned as a real value in the range [0, 1] (binary classification in this example).


keras predict_classes (docs) outputs A numpy array of class predictions. Which in your model case, the index of neuron of highest activation from your last(softmax) layer. [[0]] means that your model predicted that your test data is class 0. (usually you will be passing multiple image, and the result will look like [[0], [1], [1], [0]] )

You must convert your actual label (e.g. 'cancer', 'not cancer') into binary encoding (0 for 'cancer', 1 for 'not cancer') for binary classification. Then you will interpret your sequence output of [[0]] as having class label 'cancer'