Zagorax
Zagorax

Reputation: 11890

numpy array has different shape when I pass it as input to a keras layer

I have a keras encoder (part of an autoencoder) built this way:

input_vec = Input(shape=(200,))
encoded = Dense(20, activation='relu')(input_vec)
encoder = Model(input_vec, encoded)

I want to generate a dummy input using numpy.

>>> np.random.rand(200).shape
(200,)

But if i try to pass it as input to the encoder I get a ValueError:

>>> encoder.predict(np.random.rand(200))
>>> Traceback (most recent call last):
  File "<console>", line 1, in <module>
  File "/home/francesco/PycharmProjects/W2VAutoencoded/venv/lib/python3.6/site-packages/keras/engine/training.py", line 1817, in predict
    check_batch_axis=False)
  File "/home/francesco/PycharmProjects/W2VAutoencoded/venv/lib/python3.6/site-packages/keras/engine/training.py", line 123, in _standardize_input_data
    str(data_shape))
ValueError: Error when checking : expected input_1 to have shape (200,) but got array with shape (1,)

What am I missing?

Upvotes: 2

Views: 133

Answers (1)

benjaminplanche
benjaminplanche

Reputation: 15119

While Keras Layers (Input, Dense, etc.) take as parameters the shape(s) for a single sample, Model.predict() takes as input batched data (i.e. samples stacked over the 1st dimension).

Right now your model believes you are passing it a batch of 200 samples of shape (1,).

This would work:

batch_size = 1
encoder.predict(np.random.rand(batch_size, 200))

Upvotes: 3

Related Questions