4

I'm trying to build an autoencoder in keras based on examples in this blog post but with different layers. The model compiles but throws an error (Theano) ValueError: Input dimension mis-match. (input[0].shape[2] = 1, input[6].shape[2] = 28) ... when I run .fit().

Model:

BATCH_SIZE = 10
input_img = Input(shape=(1, 28, 28))

# encode
x = Convolution2D(32, 2, 2, border_mode='same')(input_img)
x = Convolution2D(64, 2, 2, border_mode='same')(x)
x = Flatten()(x)
x = Dense(512)(x)
x = Dense(256)(x)
encoded = Dense(128)(x)

# decode
x = Dense(256)(encoded)
x = Dense(512)(x)
x = Reshape((32, 4, 4))(x)
x = Deconvolution2D(32, 2, 2, output_shape=(BATCH_SIZE, 32, 8, 8), border_mode='same')(x)
x = Deconvolution2D(64, 2, 2, output_shape=(BATCH_SIZE, 64, 16, 16), border_mode='same')(x)
x = Deconvolution2D(1, 2, 2, output_shape=(BATCH_SIZE, 1, 32, 32), border_mode='same')(x)
decoded = Cropping2D(cropping=((0,4), (4,0)))(x)

DAE = Model(input_img, decoded)
DAE.compile(optimizer='adadelta', loss='binary_crossentropy')
user390458
  • 43
  • 3

1 Answers1

2

The code is a bit outdated, the calculation of the output shape of Deconvolution2D layer in Keras has changed.

Try

BATCH_SIZE = 10
input_img = Input(shape=(1, 28, 28))

# encode
x = Convolution2D(32, 2, 2, border_mode='same')(input_img)
x = Convolution2D(64, 2, 2, border_mode='same')(x)
x = Flatten()(x)
x = Dense(512)(x)
x = Dense(256)(x)
encoded = Dense(128)(x)

# decode
x = Dense(256)(encoded)
x = Dense(512)(x)
x = Reshape((32, 4, 4))(x)
x = Deconvolution2D(32, 2, 2, output_shape=(batch_size, 32, 8, 8), subsample=(2, 2), border_mode='valid')(x)
x = Deconvolution2D(64, 2, 2, output_shape=(batch_size, 64, 16, 16), subsample=(2, 2), border_mode='valid')(x)
x = Deconvolution2D(1, 2, 2, output_shape=(batch_size, 1, 32, 32), subsample=(2, 2), border_mode='valid')(x)
decoded = Cropping2D(cropping=((0,4), (4,0)))(x)
dontloo
  • 13,692
  • 7
  • 51
  • 80