1
from tensorflow.keras.layers import Input, Dense
from tensorflow.keras.models import Model


input_img = Input(shape=(784,))
encoded = Dense(128, activation='relu')(input_img)
encoded = Dense(64, activation='relu')(encoded)
encoded = Dense(64, activation='relu')(encoded)
encoded = Dense(64, activation='relu')(encoded)
encoded = Dense(64, activation='relu')(encoded)
encoded = Dense(64, activation='relu')(encoded)
encoded = Dense(32, activation='relu', name='encoder_output')(encoded)
decoded = Dense(64, activation='relu', name='decoder_input')(encoded)
decoded = Dense(128, activation='relu')(decoded)
decoded = Dense(128, activation='relu')(decoded)
decoded = Dense(128, activation='relu')(decoded)
decoded = Dense(128, activation='relu')(decoded)
decoded = Dense(128, activation='relu')(decoded)
decoded = Dense(784, activation='sigmoid')(decoded)
autoencoder = Model(input_img, decoded)

decoder = Model(inputs=autoencoder.get_layer('decoder_input').input,outputs=autoencoder.output)

I after running this code, I get this error. What I want to do, is to extract the decoder from the autoencoder.

I saw here, where they extract it with the index of the layer. But I don't know the index.

decoder_input = Input(shape=(encoding_dim,))
decoder = Model(decoder_input, autoencoder.layers[-1](decoder_input))

1 Answer 1

1

I'm not sure where these examples come from but dissecting the API to create these models are not the intended usage. If you look at the blog post from the author of the library, it is best to separate encoder and decoder as such:

input_img = Input(shape=(784,))
encoded = Dense(128, activation='relu')(input_img)
encoded = Dense(64, activation='relu')(encoded)
encoded = Dense(64, activation='relu')(encoded)
encoded = Dense(64, activation='relu')(encoded)
encoded = Dense(64, activation='relu')(encoded)
encoded = Dense(64, activation='relu')(encoded)
encoded = Dense(32, activation='relu')(encoded)
encoder = Model(input_img, encoded)

decoder_input = Input(shape=(32,))
decoded = Dense(64, activation='relu')(decoder_input)
decoded = Dense(128, activation='relu')(decoded)
decoded = Dense(128, activation='relu')(decoded)
decoded = Dense(128, activation='relu')(decoded)
decoded = Dense(128, activation='relu')(decoded)
decoded = Dense(128, activation='relu')(decoded)
decoded = Dense(784, activation='sigmoid')(decoded)
decoder = Model(decoder_input, decoded)

autoenc = decoder(encoder(input_img))
autoencoder = Model(input_img, autoenc)

The key thing is Model is just another layer, in fact it inherits from Layer class. So you can create smaller models and then use them just like layers.

Not the answer you're looking for? Browse other questions tagged or ask your own question.