问题
I am setting up my first neural network with keras and tensorflow. I got my input into an array of shape (60000, 28, 28), but when I try and feed it to the model I get an error that the input shape is wrong.
I have tried multiple different input shapes including (60000, 28, 28) (1, 28, 28) (28, 28) (28, 28, 1) but none of them seem to work.
model = kr.Sequential()
model.add(InputLayer(input_shape=(60000, 28, 28)))
model.add(Dense(units=784, activation='relu'))
model.add(Dense(units=392, activation='relu'))
model.add(Dense(units=196, activation='relu'))
model.add(Dense(units=10, activation='softmax'))
model.compile(loss='categorical_crossentropy', optimizer='Adam', metrics=['accuracy'])
training = model.fit(x=images_array, y=labels_array, epochs=10, batch_size=256)
I would expect it to work with input shape (60000, 28, 28) but I always get this error:
ValueError: Error when checking input: expected input_1 to have 4 dimensions, but got array with shape (60000, 28, 28)
Edit:
Thanks to everyone who answerd. cho_uc answer indeed worked, which is why I accepted it. What I shold have mentioned in the post was, that I was trying to build a model consisting only of Dense layers, so I can use it as a benchmark for future models.
I solved the input layer problem with:
images_array = images_array.reshape(-1, 28 * 28)
model.add(InputLayer(input_shape=(784, )))
回答1:
Keras Conv2D
layer performs the convolution operation. It requires its input to be a 4-dimensional array.
We have to reshape the input to ( , 1, 28, 28) or possibly to ( , 28, 28, 1), depending on your setup and backend (theano or tensorlow image layout convention).
from keras import backend as K
if K.image_data_format() == 'channels_first' :
input_shape = (1, 28, 28)
X_train = X_train.reshape(X_train.shape[0], 1, 28, 28)
X_test = X_test.reshape(X_test.shape[0], 1, 28, 28)
else:
input_shape = (28, 28, 1)
X_train = X_train.reshape(X_train.shape[0], 28, 28, 1)
X_test = X_test.reshape(X_test.shape[0], 28, 28, 1)
So, you should reshape your data to (60000, 28, 28, 1) or (60000, 1, 28, 28)
回答2:
Two corrections are required.
- TF and Keras expects image dimension as (Width, Height, Channels), channels being 3 for RGB images and 1 for greyscale images.
model.add(InputLayer(input_shape=(28, 28, 1)))
- The training input to
fit()
method must be of dimension (Number of samples, Width, Height, Channels).
assert images_array.shape == (60000, 28, 28, 1)
来源:https://stackoverflow.com/questions/56348135/error-defining-an-input-shape-in-keras-for-60000-28-28-array