I have trained and tested my model - now I want to use it to predict for a given path to an image file - how can I do this?
You can use model.predict method for doing . Will be able to help if you can provide more information
In Keras Documentation https://keras.io/models/sequential/
function is used for predicting the images in the test set.
predict(self, x, batch_size=32, verbose=0)
from keras.models import Sequential
model_cnn = your_model() # python function for your cnn model
Compile your model.
Fit your model.
Train your model.
model_cnn.predict(test_set, batch_size = your_size, verbose = 0)
I have the same question as the OP.
Here is what I’ve done.
import cv2 img = cv2.imread(path_to_one_file) print(vgg.model.predict([img])) # model is already trained
ValueError: Error when checking : expected lambda_input_2 to have 4 dimensions, but got array with shape (499, 381, 3)
I then tried to resize doing:
import cv2 img = cv2.imread(path_to_one_file) img = np.array([img]).reshape((1, 3, 224, 224)) print(vgg.model.predict([img])) # model is already trained
After that I get:
ValueError: cannot reshape array of size 570357 into shape (1,3,224,224)
There must be some preprocessing step that I’m missing. Any ideas?
Did resized the test images before using them to predict ?
Note :- Your train, test images needed to be of same size.
I tried some more resizing, but i’m not quite there yet. Below is what I’ve done.
import cv2 img = cv2.imread(path_to_one_file) img = cv2.resize(img, (244, 244)) # img has shape (244, 244, 3), we need (3, 244, 244) print(vgg.model.predict(np.array(img).reshape((1, 3, 244, 244)))) # This is were I'm confused
This gives the error:
ValueError: Error when checking : expected lambda_input_1 to have shape (None, 3, 224, 224) but got array with shape (1, 3, 244, 244)
In last line you are using a 4D tensor instead of a 3D tensor. You are training your model with shape
(img_width, img_height, num_channels) That’s correct till line 3. When using the data for prediction you have to use the same dimensions of image. Instead of 3D tensor you are using a 4D
reshape((1, 3, 244, 244)) . If you look at the ValueError you will see that [quote=“chasesc, post:6, topic:4696”]
expected lambda_input_1 to have shape (None, 3, 224, 224)
which expresses a tensor of shape
(batch_size, img_width, img_height, num_channels).
Now in line 2 you did not used a
batch_size as a dimension but during prediction you are using it as