Error when checking model input: expected convolution2d_input_1 to have 4 dimensions, but got array with shape (32, 32, 3)
Solution 1:
The input shape you have defined is the shape of a single sample. The model itself expects some array of samples as input (even if its an array of length 1).
Your output really should be 4-d, with the 1st dimension to enumerate the samples. i.e. for a single image you should return a shape of (1, 32, 32, 3).
You can find more information here under "Convolution2D"/"Input shape"
Edit: Based on Danny's comment below, if you want a batch size of 1, you can add the missing dimension using this:
image = np.expand_dims(image, axis=0)
Solution 2:
It is as simple as to Add one dimension, so I was going through the tutorial taught by Siraj Rawal on CNN Code Deployment tutorial, it was working on his terminal, but the same code was not working on my terminal, so I did some research about it and solved, I don't know if that works for you all. Here I have come up with solution;
Unsolved code lines which gives you problem:
if K.image_data_format() == 'channels_first':
x_train = x_train.reshape(x_train.shape[0], 1, img_rows, img_cols)
x_test = x_test.reshape(x_test.shape[0], 1, img_rows, img_cols)
print(x_train.shape)
input_shape = (1, img_rows, img_cols)
else:
x_train = x_train.reshape(x_train.shape[0], img_rows, img_cols)
x_test = x_test.reshape(x_test.shape[0], img_rows, img_cols)
input_shape = (img_rows, img_cols, 1)
Solved Code:
if K.image_data_format() == 'channels_first':
x_train = x_train.reshape(x_train.shape[0], 1, img_rows, img_cols)
x_test = x_test.reshape(x_test.shape[0], 1, img_rows, img_cols)
print(x_train.shape)
input_shape = (1, img_rows, img_cols)
else:
x_train = x_train.reshape(x_train.shape[0], img_rows, img_cols, 1)
x_test = x_test.reshape(x_test.shape[0], img_rows, img_cols, 1)
input_shape = (img_rows, img_cols, 1)
Please share the feedback here if that worked for you.
Solution 3:
Probably very trivial, but I solved it by just converting the input to numpy array.
For the neural network architecture,
model = Sequential()
model.add(Conv2D(32, (5, 5), activation="relu", input_shape=(32, 32, 3)))
When the input was,
n_train = len(train_y_raw)
train_X = [train_X_raw[:,:,:,i] for i in range(n_train)]
train_y = [train_y_raw[i][0] for i in range(n_train)]
I got the error,
But when I changed it to,
n_train = len(train_y_raw)
train_X = np.asarray([train_X_raw[:,:,:,i] for i in range(n_train)])
train_y = np.asarray([train_y_raw[i][0] for i in range(n_train)])
It fixed the issue.