Search code examples
pythonkerasautoencoder

Save Autoencoder's encoder model


I use the ModelCheckpoint to save the best autoencoder model as below:

checkpoint = ModelCheckpoint("ae_model", monitor='val_loss', verbose=1, save_best_only=True, mode='max')
callbacks_list = [checkpoint]
# encoder layer
encoded = Dense(128, activation='relu')(input)
encoder_output = Dense(10)(encoded)
# decoder layer
decoded = Dense(128, activation='relu')(decoded)
# construct the autoencoder model
autoencoder = Model(input=input_img, output=decoded)
# construct the encoder model
encoder = Model(input=input_img, output=encoder_output)
autoencoder.compile(loss='mse', optimizer='adam')
autoencoder.fit(x_train, x_train, epochs=100, batch_size=10,
                shuffle=True, validation_split=0.33, 
                callbacks=callbacks_list)

But, how can I save the encoder model as well when the best best autoencoder model saved? So I can reuse the encoder model like below.

from keras.models import load_model
encoder = load_model('encoder_model')

Or Is there alternative way to separate encoder from autoencoder model?

from keras.models import load_model
autoencoder = load_model('autoencoder_model')
encoder = autoencoder.???

Thanks,


Solution

  • You can write small custom ModelCheckpoint class that replaces which model should be saved:

    class EncoderCheckpoint(ModelCheckpoint):
      def __init__(self, filepath, **kwargs):
        super().__init__(filepath, **kwargs)
        self.model = encoder # we manually set encoder model
    
      def set_model(self, model):
        pass # ignore when Keras tries to set autoencoder model