Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Expected shape (None, 8) but got array with shape (8,1)

Tags:

python

keras

I have the following code,

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

# load dataset
dataset = np.loadtxt("data.csv", delimiter=",")
# split into input (X) and output (Y) variables
X = dataset[:, 0:8]
Y = dataset[:, 8]
# create model
model = Sequential()
model.add(Dense(8, activation="relu", input_dim=8, kernel_initializer="uniform"))
model.add(Dense(12, activation="relu", kernel_initializer="uniform"))
model.add(Dense(1, activation="sigmoid", kernel_initializer="uniform"))
# Compile model
model.compile(loss='binary_crossentropy', optimizer='adam', metrics=['accuracy'])
# Fit the model
model.fit(X, Y, epochs=150, batch_size=10,  verbose=2)
# calculate predictions
test = np.array([6,148,72,35,0,33.6,0.627,50])
predictions = model.predict(test)
# round predictions
rounded = [round(x[0]) for x in predictions]
print(rounded)

When I run the program, it gives me the following error.

ValueError: Error when checking : expected dense_1_input to have shape (None, 8) but got array with shape (8,1)

I know there are a lot of duplicates to this question, I have tried all of them but it still gives me the same errors. How do I solve it?

like image 894
Nikhil Raghavendra Avatar asked Aug 04 '17 06:08

Nikhil Raghavendra


1 Answers

Eventhough we don't see the full error trace, I think that the model learns and the error comes at the line :

predictions = model.predict(test)

Please confirm this.

The prediction fails because what you should always feed the network with is a numpy array of shape (number_of_samples_to_predict, input_shape). There is always an additionnal dimension at the beginning, this is where you pile up all of the samples that you want to predict. When there is only one sample, you still have to feed a [1, input_shape] array.

To fix this use define your test input like this :

test = np.array([[6,148,72,35,0,33.6,0.627,50]])

now test has shape (1,8) which should run as the model expects (?,8).

like image 177
Nassim Ben Avatar answered Oct 30 '22 07:10

Nassim Ben