2
votes

I'm trying to train a model on features i extracted from some images, model trains fine, but when i try model.predict it gives me this error. " expected dense_input to have shape (7,) but got array with shape (1,)" i have the knowledge about the shape of the input but the error is just weird. it makes no sense to me right now i tried to print the shape of the input i am giving to model.predict and its fine.

import numpy as np

from tensorflow.keras.models import Sequential
from tensorflow.keras.layers import Dense, Activation

trainX = np.array(train_set)

trainY = np.array(train_labels)

model = Sequential()

model.add(Dense(8, input_dim=7, activation='relu'))
model.add(Dense(1))
model.compile(loss='mean_squared_error', optimizer='adam')
model.fit(trainX, trainY, nb_epoch=1200, batch_size=2, verbose=2)
model.save('my_model.h5') 

for i in np.array(test_set):
    print(i.shape)
    dataPrediction = model.predict(i)
    print (dataPrediction, '<--- Predicted number')
    print (test_labels[i],' <-- Correct answer \n')

print(i.shape) gives me (7,) yet it gives me error Error when checking input: expected dense_input to have shape (7,) but got array with shape (1,)

2

2 Answers

2
votes

That's because your model expects an array of samples, but you're giving it a single sample at a time.

It therefore treated each feature in your sample as an individual sample of shape (1,), which didn't make sense to it since you presumably had 7 features and it therefore expected a sample of shape (7,).

You can just do model.predict(np.array(test_set)).

2
votes

try

dataPrediction = model.predict(np.expand_dims(i,axis=0))