我正在尝试为Keras博客https://blog.keras.io/building-autoencoders-in-keras.html上的Convolutional Autoencoder运行以下代码。但是,我收到了错误消息:
input_img = Input(shape=(1, 28, 28))
x = Convolution2D(16, 3, 3, activation='relu', border_mode='same')(input_img)
x = MaxPooling2D((2, 2), border_mode='same')(x)
x = Convolution2D(8, 3, 3, activation='relu', border_mode='same')(x)
x = MaxPooling2D((2, 2), border_mode='same')(x)
x = Convolution2D(8, 3, 3, activation='relu', border_mode='same')(x)
encoded = MaxPooling2D((2, 2), border_mode='same')(x)
# at this point the representation is (8, 4, 4) i.e. 128-dimensional
x = Convolution2D(8, 3, 3, activation='relu', border_mode='same')(encoded)
x = UpSampling2D((2, 2))(x)
x = Convolution2D(8, 3, 3, activation='relu', border_mode='same')(x)
x = UpSampling2D((2, 2))(x)
x = Convolution2D(16, 3, 3, activation='relu')(x)
x = UpSampling2D((2, 2))(x)
decoded = Convolution2D(1, 3, 3, activation='sigmoid', border_mode='same')(x)
print(decoded.get_shape())
autoencoder = Model(input_img, decoded)
autoencoder.compile(optimizer='adadelta',
loss='binary_crossentropy'
)
autoencoder.fit(x_train, x_train,
nb_epoch=50,
batch_size=128,
shuffle=True,
validation_data=(x_test, x_test)
)
---------------------------------------------------------------------------
Exception Traceback (most recent call last)
<ipython-input-25-5ca753acfdbb> in <module>()
28 batch_size=128,
29 shuffle=True,
---> 30 validation_data=(x_test, x_test)
31 )
C:\Users\Alexander\Anaconda3\lib\site-packages\keras\engine\training.py in fit(self, x, y, batch_size, nb_epoch, verbose, callbacks, validation_split, validation_data, shuffle, class_weight, sample_weight, initial_epoch)
1036 class_weight=class_weight,
1037 check_batch_dim=False,
-> 1038 batch_size=batch_size)
1039 # prepare validation data
1040 if validation_data:
C:\Users\Alexander\Anaconda3\lib\site-packages\keras\engine\training.py in _standardize_user_data(self, x, y, sample_weight, class_weight, check_batch_dim, batch_size)
965 output_shapes,
966 check_batch_dim=False,
--> 967 exception_prefix='model target')
968 sample_weights = standardize_sample_weights(sample_weight,
969 self.output_names)
C:\Users\Alexander\Anaconda3\lib\site-packages\keras\engine\training.py in standardize_input_data(data, names, shapes, check_batch_dim, exception_prefix)
109 ' to have shape ' + str(shapes[i]) +
110 ' but got array with shape ' +
--> 111 str(array.shape))
112 return arrays
113
Exception: Error when checking model target: expected convolution2d_92 to have shape (None, 4, 28, 1) but got array with shape (60000, 1, 28, 28)
我打印出来的解码维度为(?, 4, 28, 1)
,在给定错误消息的情况下,似乎是模型所期望的。谢谢你的帮助。
答案 0 :(得分:0)
问题在于,当我应该使用Tensorflow后端时,我意外地使用了Theano后端。在theano后端,第一个坐标表示单个张量的形状,但它在张量流中是相反的。例如,对于input_img
,在Theano中它的形状为(1, 28, 28)
,但在Tensorflow中为(28, 28, 1)
。