Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Keras/Tensorflow predict: error in array shape

I'm following the Keras CIFAR10 tutorial here. The only changes I made were:

[a] added to the end of tutorial file

model.save_weights('./weights.h5', overwrite=True)

[b] changed ~./keras/keras.json to

{"floatx": "float32", "backend": "tensorflow", "epsilon": 1e-07}

I can run the model successfully.

Then I want to test a single image against the trained model. My code:

[... similar to tutorial file with model being created and compiled...]
...
model = Sequential()
...
model.compile()

model.load_weights('./ddx_weights.h5')

img = cv2.imread('car.jpeg', -1) # this is is a 32x32 RGB image
img = np.array(img)
y_pred = model.predict_classes(img, 1)
print(y_pred)

I get this error:

ValueError: Cannot feed value of shape (1, 32, 3) for Tensor 'convolution2d_input_1:0', which has shape '(?, 3, 32, 32)'

What is the correct way of reshaping the input data for a single image to be tested?

I have not added "image_dim_ordering": "tf" in ./keras/keras.json.

like image 511
pepe Avatar asked Jun 06 '16 21:06

pepe


1 Answers

You have to reshape the input image to have a shape of [?, 3, 32, 32] where ? is the batch size. In your case, since you have 1 image the batch size is 1, so you can do:

img = np.array(img)
img = img.reshape((1, 3, 32, 32))
like image 102
Olivier Moindrot Avatar answered Nov 19 '22 04:11

Olivier Moindrot