Inverse of keras.Flatten for building autoencoder

Viewed 1498

My goal is to build a convolutional autoencoder that encodes input image to flat vector of size (10,1). I followed the example from keras documentation and modified it for my purposes. Unfortunetely, the model like this:

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

x = Conv2D(16, (3, 3), activation='relu', padding='same')(input_img)
x = MaxPooling2D((2, 2), padding='same')(x)
x = Conv2D(8, (3, 3), activation='relu', padding='same')(x)
x = MaxPooling2D((2, 2), padding='same')(x)
x = Flatten()(x)

encoded = Dense(units = 10, activation = 'relu')(x)


x = Conv2D(8, (3, 3), activation='relu', padding='same')(encoded)
x = UpSampling2D((2, 2))(x)
x = Conv2D(16, (3, 3), activation='relu')(x)
x = UpSampling2D((2, 2))(x)
decoded = Conv2D(1, (3, 3), activation='sigmoid', padding='same')(x)

autoencoder = Model(input_img, decoded)

gives me

ValueError: Input 0 is incompatible with layer conv2d_39: expected ndim=4, found ndim=2

I think I should add some layer to my Decoder to inverse the effect of Flatten, but wasn't really sure which one. Can you help?

1 Answers

Why do you want to have specifically (10,1) shape for the vector? You are trying to then do convolutions on that with kernel of size 3x3, which does not really make sense.

The shape a convolutional layer takes in has height, width and channels. The output of the dense layer has to be reshaped which can be done with Reshape layer. You can then reshape it to for example 5x2 with single channel.

encoded = Reshape((5, 2, 1))(encoded)
Related