Keras: Getting ValueError: Error when checking input: expected conv2d_1_input to have 4 dimensions, but got array with shape (315, 720, 1280)

Created on 27 Apr 2018  路  13Comments  路  Source: keras-team/keras

Hi,

I am trying to train a model on some grayscale images. The model I am using is:

model = Sequential()
model.add(Convolution2D(8, 3, 3, input_shape=(720, 1280,1)))
model.add(Activation('relu'))
model.add(MaxPooling2D(pool_size=(2, 2)))
model.add(BatchNormalization())

model.add(Convolution2D(16, 3, 3))
model.add(Activation('relu'))
model.add(MaxPooling2D(pool_size=(2, 2)))
model.add(BatchNormalization())
#model.add(Dropout(0.6))

model.add(Convolution2D(32, 3, 3))
model.add(Activation('relu'))
model.add(MaxPooling2D(pool_size=(2, 2)))
model.add(BatchNormalization())

model.add(Convolution2D(64, 3, 3))
model.add(Activation('relu'))
model.add(MaxPooling2D(pool_size=(2, 2)))
model.add(BatchNormalization())
model.add(Dropout(0.5))

model.add(Flatten())  # this converts our 3D feature maps to 1D feature vectors
model.add(Dense(64))
model.add(Activation('relu'))
model.add(Dropout(0.5))
model.add(Dense(1))
model.add(Activation('sigmoid'))

Then I compile it:

model.compile(optimizer='rmsprop',
              loss='categorical_crossentropy',
              metrics=['accuracy'])

and then fit it:

model.fit(np.array(X_train), np.array(y_train_cat), batch_size=32,
          epochs=10, verbose=1, validation_split=0.1)

The shape of the image is (1280,720)
I get the error:

ValueError: Error when checking input: expected conv2d_1_input to have 4 dimensions, but got array with shape (315, 720, 1280)

If I don't use the np.array in fit, I get the following error:

Error when checking model input: the list of Numpy arrays that you are passing to your model is not the size the model expected. Expected to see 1 array(s), but instead got the following list of 315 arrays:

Can you please suggest what I should do? I have tried to resize it to 3D, something like (1280,720,1), but it's not working.

Most helpful comment

I used he numpy function to change the dimention to the image. The exact function I'll send soon.

All 13 comments

You need X_train to have a fourth dimension. Just like the error message says.
X_train.reshape([-1,720, 1280,1]).

This issue isn't related to a bug/enhancement/feature request or other accepted types of issue.

To ask questions, please see the following resources :

Thanks!

If you think I made a mistake, please re-open this issue.

@Dreg360, I tried that but I think I forgot to put square braces. Gosh, I'll try that.

@Dref360, I tried to reshape. It's not changing the shape of the image. Instead of (720,1280,1) as output, it's showing (720,1280).

may I know How you got rid from this issue

I used he numpy function to change the dimention to the image. The exact function I'll send soon.

@Flock1, I am having the same issue. I have opened the issue in https://github.com/keras-team/keras/issues/11180.
Could you take a look for that? thanks a lot!

Hey @1q2q1q1q, use the np.resize function to solve that. I apologise for the late response. But use np.resize(img, (-1, <image shape>). That should solve the issue.

Hey @1q2q1q1q, use the np.resize function to solve that. I apologise for the late response. But use np.resize(img, (-1, <image shape>). That should solve the issue.

@Flock1 Ok, but where exactly ?

I think you should write this to reshape your X_train data:
X_train = X_train.reshape(X_train.shape[0], 720, 1280, 1)

enjoyedcoding

SAME ISSUE

model = models.Sequential()

model.add(layers.Conv2D(32, (3, 3), input_shape=(150,150, 3)))
model.add(layers.Activation('relu'))
model.add(layers.MaxPooling2D(pool_size=(2, 2)))

model.add(layers.Conv2D(32, (3, 3)))
model.add(layers.Activation('relu'))
model.add(layers.MaxPooling2D(pool_size=(2, 2)))

model.add(layers.Conv2D(64, (3, 3)))
model.add(layers.Activation('relu'))
model.add(layers.MaxPooling2D(pool_size=(2, 2)))

model.add(layers.Flatten())
model.add(layers.Dense(64))
model.add(layers.Activation('relu'))
model.add(layers.Dropout(0.5))
model.add(layers.Dense(1))
model.add(layers.Activation('sigmoid'))

model.compile(loss='binary_crossentropy',
optimizer='rmsprop',
metrics=['accuracy'])
model.add(layers.Flatten())
model.add(layers.Dense(64,activation='relu'))
model.add(layers.Dense(10,activation='softmax'))
model.compile(optimizer='adam',
loss='sparse_categorical_crossentropy',
metrics=['accuracy'])

history=model.fit(image, onehot_encoded,batch_size=50, epochs=10)

ValueError Traceback (most recent call last)
in ()
3 metrics=['accuracy'])
4
----> 5 history=model.fit(image, onehot_encoded,batch_size=50, epochs=10)

3 frames
/usr/local/lib/python3.6/dist-packages/tensorflow_core/python/keras/engine/training_utils.py in standardize_input_data(data, names, shapes, check_batch_axis, exception_prefix)
561 ': expected ' + names[i] + ' to have ' +
562 str(len(shape)) + ' dimensions, but got array '
--> 563 'with shape ' + str(data_shape))
564 if not check_batch_axis:
565 data_shape = data_shape[1:]

ValueError: Error when checking input: expected conv2d_22_input to have 4 dimensions, but got array with shape (287, 300, 3)

I tackled this error by reshaping the training images. You should reshape your training data by the "reshape" function.e.g. X_train.reshape(10,287,30,3). Then while defining your input_shape for the convolutional layer use input_shape as "input_shape=287,30,3". Hope it works for you.

In reshaping our test images, we should be careful with input_size of the image like :

model.predict(X_train.reshape(10,28,28,1) -->for 10 input images.

If we want to predict for single instance of image, we should consider only one image but not number of features. (Features could be what ever, like 789 or 287 e.t.c..)

model.predict(X_train.reshape(1,28,28,3))

I got the same error. How do I solve this?

Model Summary:


Layer (type) Output Shape Param # Connected to

input_1 (InputLayer) [(None, 1024, 1024, 1)] 0


lambda (Lambda) (None, 1024, 1024, 1 0 input_1[0][0]


conv2d (Conv2D) (None, 1024, 1024, 6 1664 lambda[0][0]


conv2d_1 (Conv2D) (None, 1024, 1024, 6 102464 conv2d[0][0]


max_pooling2d (MaxPooling2D) (None, 512, 512, 64) 0 conv2d_1[0][0]


conv2d_2 (Conv2D) (None, 512, 512, 192 307392 max_pooling2d[0][0]


conv2d_3 (Conv2D) (None, 512, 512, 192 921792 conv2d_2[0][0]


max_pooling2d_1 (MaxPooling2D) (None, 256, 256, 192 0 conv2d_3[0][0]


conv2d_4 (Conv2D) (None, 256, 256, 480 2304480 max_pooling2d_1[0][0]


conv2d_5 (Conv2D) (None, 256, 256, 480 5760480 conv2d_4[0][0]


max_pooling2d_2 (MaxPooling2D) (None, 128, 128, 480 0 conv2d_5[0][0]


conv2d_6 (Conv2D) (None, 128, 128, 832 9984832 max_pooling2d_2[0][0]


conv2d_7 (Conv2D) (None, 128, 128, 832 17306432 conv2d_6[0][0]


up_sampling2d (UpSampling2D) (None, 256, 256, 832 0 conv2d_7[0][0]


concatenate (Concatenate) (None, 256, 256, 131 0 up_sampling2d[0][0]
conv2d_5[0][0]


conv2d_8 (Conv2D) (None, 256, 256, 480 15744480 concatenate[0][0]


conv2d_9 (Conv2D) (None, 256, 256, 480 5760480 conv2d_8[0][0]


up_sampling2d_1 (UpSampling2D) (None, 512, 512, 480 0 conv2d_9[0][0]


concatenate_1 (Concatenate) (None, 512, 512, 672 0 up_sampling2d_1[0][0]
conv2d_3[0][0]


conv2d_10 (Conv2D) (None, 512, 512, 192 3225792 concatenate_1[0][0]


conv2d_11 (Conv2D) (None, 512, 512, 192 921792 conv2d_10[0][0]


up_sampling2d_2 (UpSampling2D) (None, 1024, 1024, 1 0 conv2d_11[0][0]


concatenate_2 (Concatenate) (None, 1024, 1024, 2 0 up_sampling2d_2[0][0]
conv2d_1[0][0]


conv2d_12 (Conv2D) (None, 1024, 1024, 6 409664 concatenate_2[0][0]


conv2d_13 (Conv2D) (None, 1024, 1024, 6 102464 conv2d_12[0][0]


conv2d_14 (Conv2D) (None, 1024, 1024, 2 514 conv2d_13[0][0]

Total params: 62,854,722
Trainable params: 62,854,722
Non-trainable params: 0


Error:
Traceback (most recent call last):

File "", line 1, in
runfile('C:/Users/21116643/Desktop/High School/2020 - Intern/classifySpine.py', wdir='C:/Users/21116643/Desktop/High School/2020 - Intern')

File "D:Pythonlibsite-packagesspyder_kernelscustomizespydercustomize.py", line 827, in runfile
execfile(filename, namespace)

File "D:Pythonlibsite-packagesspyder_kernelscustomizespydercustomize.py", line 110, in execfile
exec(compile(f.read(), filename, 'exec'), namespace)

File "C:/Users/21116643/Desktop/High School/2020 - Intern/classifySpine.py", line 155, in
history=model.fit(x_img, mask, nb_epoch=100, batch_size=64, verbose=2)

File "D:Pythonlibsite-packagestensorflow_corepythonkerasenginetraining.py", line 819, in fit
use_multiprocessing=use_multiprocessing)

File "D:Pythonlibsite-packagestensorflow_corepythonkerasenginetraining_v2.py", line 235, in fit
use_multiprocessing=use_multiprocessing)

File "D:Pythonlibsite-packagestensorflow_corepythonkerasenginetraining_v2.py", line 593, in _process_training_inputs
use_multiprocessing=use_multiprocessing)

File "D:Pythonlibsite-packagestensorflow_corepythonkerasenginetraining_v2.py", line 646, in _process_inputs
x, y, sample_weight=sample_weights)

File "D:Pythonlibsite-packagestensorflow_corepythonkerasenginetraining.py", line 2383, in _standardize_user_data
batch_size=batch_size)

File "D:Pythonlibsite-packagestensorflow_corepythonkerasenginetraining.py", line 2410, in _standardize_tensors
exception_prefix='input')

File "D:Pythonlibsite-packagestensorflow_corepythonkerasenginetraining_utils.py", line 573, in standardize_input_data
'with shape ' + str(data_shape))

ValueError: Error when checking input: expected input_1 to have 4 dimensions, but got array with shape (1024, 1024, 1)

Was this page helpful?
0 / 5 - 0 ratings