Error when checking model input: expected convolution2d_input_1 to have shape (None, 3, 32, 32) but got array with shape (50000, 32, 32, 3)

16,113

If you print x_train.shape you will see the shape being (50000, 32, 32, 3) whereas you have given input_shape=(3, 32, 32) in the first layer. The error simply says that the expected input shape and data given are different.

All you need to do is give input_shape=(32, 32, 3). Also if you use this shape then you must use tf as your image ordering. backend.set_image_dim_ordering('tf').

Otherwise you can permute the axis of data.

x_train = x_train.transpose(0,3,1,2)
x_test = x_test.transpose(0,3,1,2)
print x_train.shape
Share:
16,113
Mona Jalal
Author by

Mona Jalal

contact me at [email protected] I am a 5th-year computer science Ph.D. Candidate at Boston University advised by Professor Vijaya Kolachalama in computer vision as the area of study. Currently, I am working on my proposal exam and thesis on the use of efficient computer vision and deep learning for cancer detection in H&E stained digital pathology images.

Updated on June 27, 2022

Comments

  • Mona Jalal
    Mona Jalal almost 2 years

    Can someone please guide how to fix this error? I just started on Keras:

     1 from keras.datasets import cifar10
      2 from matplotlib import pyplot
      3 from scipy.misc import toimage
      4 
      5 (x_train, y_train), (x_test, y_test) = cifar10.load_data()
      6 for i in range(0, 9):
      7     pyplot.subplot(330 + 1 + i)
      8     pyplot.imshow(toimage(x_train[i]))
      9 pyplot.show()
     10 
     11 import numpy
     12 from keras.models import Sequential
     13 from keras.layers import Dense
     14 from keras.layers import Dropout
     15 from keras.layers import Flatten
     16 from keras.constraints import maxnorm
     17 from keras.optimizers import SGD
     18 from keras.layers.convolutional import Convolution2D
     19 from keras.layers.convolutional import MaxPooling2D
     20 from keras.utils import np_utils
     21 from keras import backend
     22 backend.set_image_dim_ordering('th')
     23 
     24 seed = 7
     25 numpy.random.seed(seed)
     26 
     27 x_train = x_train.astype('float32')
     28 x_test = x_test.astype('float32')
     29 x_train = x_train / 255.0
     30 x_test = x_test / 255.0
     31 
     32 y_train = np_utils.to_categorical(y_train)
     33 y_test = np_utils.to_categorical(y_test)
     34 num_classes = y_test.shape[1]
     35 
     36 model = Sequential()
     37 model.add(Convolution2D(32, 3, 3, input_shape=(3, 32, 32), border_mode='same', activation='relu', W_constraint=maxnorm(3)))
     38 model.add(Dropout(0.2))
     39 model.add(Convolution2D(32, 3, 3, activation='relu', border_mode='same', W_constraint=maxnorm(3)))
     40 model.add(Flatten())
     41 model.add(Dense(512, activation='relu', W_constraint=maxnorm(3)))
     42 model.add(Dropout(0.5))
     43 model.add(Dense(num_classes, activation='softmax'))
     44 
     45 epochs = 25
     46 learning_rate = 0.01
     47 learning_rate_decay = learning_rate/epochs
     48 sgd = SGD(lr=learning_rate, momentum=0.9, decay=learning_rate_decay, nesterov=False)
     49 model.compile(loss='categorical_crossentropy', optimizer=sgd, metrics=['accuracy'])
     50 print(model.summary())
     51 
     52 model.fit(x_train, y_train, validation_data=(x_test, y_test), nb_epoch=epochs, batch_size=32)
     53 scores = model.evaluate(x_test, y_test, verbose=0)
     54 print("Accuracy: %.2f%%" % (scores[1]*100))
    

    Output is:

    mona@pascal:/data/wd1$ python test_keras.py 
    Using TensorFlow backend.
    I tensorflow/stream_executor/dso_loader.cc:111] successfully opened CUDA library libcublas.so.8.0 locally
    I tensorflow/stream_executor/dso_loader.cc:111] successfully opened CUDA library libcudnn.so.5.0 locally
    I tensorflow/stream_executor/dso_loader.cc:111] successfully opened CUDA library libcufft.so.8.0 locally
    I tensorflow/stream_executor/dso_loader.cc:111] successfully opened CUDA library libcuda.so.1 locally
    I tensorflow/stream_executor/dso_loader.cc:111] successfully opened CUDA library libcurand.so.8.0 locally
    ____________________________________________________________________________________________________
    Layer (type)                     Output Shape          Param #     Connected to                     
    ====================================================================================================
    convolution2d_1 (Convolution2D)  (None, 32, 32, 32)    896         convolution2d_input_1[0][0]      
    ____________________________________________________________________________________________________
    dropout_1 (Dropout)              (None, 32, 32, 32)    0           convolution2d_1[0][0]            
    ____________________________________________________________________________________________________
    convolution2d_2 (Convolution2D)  (None, 32, 32, 32)    9248        dropout_1[0][0]                  
    ____________________________________________________________________________________________________
    flatten_1 (Flatten)              (None, 32768)         0           convolution2d_2[0][0]            
    ____________________________________________________________________________________________________
    dense_1 (Dense)                  (None, 512)           16777728    flatten_1[0][0]                  
    ____________________________________________________________________________________________________
    dropout_2 (Dropout)              (None, 512)           0           dense_1[0][0]                    
    ____________________________________________________________________________________________________
    dense_2 (Dense)                  (None, 10)            5130        dropout_2[0][0]                  
    ====================================================================================================
    Total params: 16,793,002
    Trainable params: 16,793,002
    Non-trainable params: 0
    ____________________________________________________________________________________________________
    None
    Traceback (most recent call last):
      File "test_keras.py", line 52, in <module>
        model.fit(x_train, y_train, validation_data=(x_test, y_test), nb_epoch=epochs, batch_size=32)
      File "/usr/local/lib/python2.7/dist-packages/keras/models.py", line 664, in fit
        sample_weight=sample_weight)
      File "/usr/local/lib/python2.7/dist-packages/keras/engine/training.py", line 1068, in fit
        batch_size=batch_size)
      File "/usr/local/lib/python2.7/dist-packages/keras/engine/training.py", line 981, in _standardize_user_data
        exception_prefix='model input')
      File "/usr/local/lib/python2.7/dist-packages/keras/engine/training.py", line 113, in standardize_input_data
        str(array.shape))
    ValueError: Error when checking model input: expected convolution2d_input_1 to have shape (None, 3, 32, 32) but got array with shape (50000, 32, 32, 3)