Matt
Matt

Reputation: 189

NP array input to a Neural Network results in shape error

I have a dummy np array:

model_input = np.array(range(10))

Which I am trying to put through a dummy neural network:

model = Sequential()
model.add(Dense(units = 50, input_shape = model_input.shape, activation = 'relu'))
model.add(Dense(units = 50, activation = 'relu'))
model.add(Dense(3))
model.compile(loss = 'mse', optimizer = Adam(lr = 0.01), metrics = ['accuracy'])

However, when I run

model.predict(model_input)

I receive an error:

Error when checking : expected dense_300_input to have shape (10,) but got array with shape (1,)

This doesn't make much sense to me, as I have told the neural network that the shape of the input is equal to the shape of the array I am putting into it, and making no modifications to it before running the predict function. I feel that I am misunderstanding something fundamental here, but am not sure what it is.

My imports are:

import numpy as np
from keras.models import Sequential
from keras.layers import Dense
from keras.optimizers import Adam

Upvotes: 2

Views: 426

Answers (1)

Mathias Müller
Mathias Müller

Reputation: 22617

Keras expects inputs to have a batch dimension. Your batch size can be 1, but input arrays still need to have a batch dimension, for instance like this:

model_input = np.array([model_input])

or one of several alternatives, such as

model_input = np.expand_dims(model_input, axis=0)
model_input = model_input[None,:]

Output

array([[0.759178  , 0.40589622, 2.0082092 ]], dtype=float32)

Upvotes: 2

Related Questions