Mate de Vita
Mate de Vita

Reputation: 1325

Invalid numpy shape in keras model

I would like to build a neural network which accepts a simple 1-dimensional input vector. However, the following code gives me an error:

import numpy as np  
from keras.models import Model
from keras.layers import Input, Dense

input_ = Input((311,))
x = Dense(200)(input_)
output = Dense(100)(x)
nn = Model([input_], [output])
nn.compile('SGD', loss='mean_squared_error')
nn.predict(np.zeros(311))

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

This is strange to me because print(np.zeros(311).shape) prints (311,) as expected.

Changing np.zeros(311) to np.zeros((311,)) doesn't change anything and replacing Input((311,)) with Input(311) doesn't work, since Input expects a shape tuple:

TypeError: 'int' object is not iterable

How do I properly provide a single-dimension vector to a keras model?

Upvotes: 4

Views: 1033

Answers (1)

IonicSolutions
IonicSolutions

Reputation: 2599

The first dimension for predict has to be the batch dimension, i.e. predict(np.zeros(shape=(1, 311))) should work.

See the documentation for more details.

Upvotes: 3

Related Questions