检查模型输入时出错:预期卷积2d_input_1具有形状(无,3,32,32)但是具有形状的数组(50000,32,32,3)

时间:2017-01-20 20:36:47

标签: python tensorflow deep-learning keras

有人可以指导如何解决此错误吗?我刚开始谈起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))

输出是:

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)

1 个答案:

答案 0 :(得分:12)

如果您打印x_train.shape,您会看到形状为(50000, 32, 32, 3),而您在第一层中提供了input_shape=(3, 32, 32)。该错误只是说预期的输入形状和给定​​的数据是不同的。

您需要做的只是input_shape=(32, 32, 3)。此外,如果您使用此形状,则必须使用tf作为图像排序。 backend.set_image_dim_ordering('tf')

否则您可以置换数据轴。

x_train = x_train.transpose(0,3,1,2)
x_test = x_test.transpose(0,3,1,2)
print x_train.shape