2

I am trying to load a Keras model and make predictions with it and run into a strange error. An minimal example is the following:

from keras import models
import numpy as np

model = models.load_model('model_4hiddenLayers_16unitsPerLayer_relu_learningRate0p0001.h5')
x = np.ones(36, dtype=float)
prediction = model.predict(x )

The model expects an input shape of (36,), which should be the shape of x, which I verified:

print('x.shape={}'.format(x.shape) )

gives :

x.shape=(36,)

However when running this code I get the following error message:

ValueError: Error when checking : expected batch_normalization_1_input to have shape (36,) but got array with shape (1,)

What am I missing here? Thanks for the help.

Some additional info : I am using keras version 2.1.4 with TensorFlow as backend.

W. Verbeke
  • 141
  • 1
  • 5

1 Answers1

2

I figured out the issue. The "predict" function expects a batch of input arrays, so it expects x to have shape (n, 36) where n is the number of examples. After adding :

x = x.reshape( (1,36) )

the code works fine

W. Verbeke
  • 141
  • 1
  • 5
  • Is this to be added before building the model or before model based prediction only? – AAI Jan 04 '20 at 01:09
  • This is for the model based prediction with one sample. But for training, the array you give similarly needs to be of shape (number_of_samples, number_of_features ), like the (n,36) above. – W. Verbeke Jan 05 '20 at 11:21