1

I have trained an auto-encoder decoder using Tensorflow Keras

x_train = np.reshape(x_train, (len(x_train), n_row,n_col, 1))
x_test = np.reshape(x_test, (len(x_test),  n_row,n_col, 1))


input_img = Input(shape=(n_row,n_col, 1))

x = Convolution2D(16, (10, 10), activation='relu', padding='same')(input_img)
x = MaxPooling2D((5, 5), padding='same')(x)
x = Convolution2D(8, (2, 2), activation='relu', padding='same')(x)
x = MaxPooling2D((3, 3), padding='same')(x)
x = Convolution2D(8, (3, 3), activation='relu', padding='same')(x)
encoded = MaxPooling2D((2, 2), padding='same')(x)

x = Convolution2D(8, (2, 2), activation='relu', padding='same')(encoded)
x = UpSampling2D((3, 3))(x)
x = Convolution2D(8, (3, 3), activation='relu', padding='same')(x)
x = UpSampling2D((5, 5))(x)
x = Convolution2D(16, (10, 10), activation='relu', padding='same')(x)
x = UpSampling2D((2, 2))(x)
x = Cropping2D(cropping=((5, 0), (1, 0)), data_format=None)(x)

decoded = Convolution2D(1, (10, 10), activation='sigmoid', padding='same')(x)

autoencoder = Model(inputs=input_img, outputs=decoded)

autoencoder.compile(optimizer='adam', loss='mse')

I can save the total autoencoder model by using

autoencoder.save('...')

How can I save and access to the encoder and to the decoder separately from ?

SC_these
  • 31
  • 4

2 Answers2

0

Since you have saved the autoencoder you can extract the encoder and decoder from the saved autoencoder likewise:

autoencoder= K.models.load_model('your_saved_autoencoder')

encoder = Model(autoencoder.input, autoencoder.layers[-2].output)

decoder_input = Input(shape=(encoding_dim,))
decoder = Model(decoder_input, autoencoder.layers[-1](decoder_input))
Shivam Roy
  • 1,961
  • 3
  • 10
  • 23
  • 1
    Thank you for your answer. However, since I have a deep autoencoder, autoencoder.layers[-1] doesn't work here – SC_these Jun 06 '21 at 13:41
  • I've looked around a bit for your specific problem, and I think the way to save the encoder and decoder independently would be to create them as seperate models and then save them as you saved the auto encoder. You can refer to [this answer](https://stackoverflow.com/a/54931203/15604484) for more clarity : – Shivam Roy Jun 06 '21 at 18:27
0

You need to assign a unique name for last layer of encoder and decoder then you can reconstruct the encoder and decoder from autoencoder like this:

    encoderLayer = autoEncoder.get_layer("encoder")
    assert(encoderLayer != None)
    
    decoderLayer = autoEncoder.get_layer("decoder")
    assert(decoderLayer != None)

    encoder = Keras.Model(
        autoEncoder.input, 
        encoderLayer.output
    )

    decoder = Keras.Model(
        encoderLayer.output, 
        decoderLayer.output
    )
Mohammad f
  • 961
  • 10
  • 11