Skip to content
Advertisement

How to save Keras encoder and decoder separately?

I have created an autoencoder using a separate encoder and decoder as described in this link.

Split autoencoder on encoder and decoder keras

I am checkpointing my autoencoder as followed. How do I save the encoder and decoder separately corresponding to the autoencoder? Alternatively, can I extract deep encoder and decoder from my save autoencoder?

checkpoint = ModelCheckpoint(filepath, monitor='val_accuracy', verbose = 1, save_best_only=True, mode='max')
callbacks_list = [checkpoint]

autoencoder.fit(
    x=x_train,
    y=x_train,
    epochs=10,
    batch_size=128,
    shuffle=True,
    validation_data=(x_test, x_test),
    callbacks=callbacks_list
)

Advertisement

Answer

You could try to overwrite the autoencoder’s save function, which the ModelCheckpoint uses, to have it save the encoder and decoder Models separately instead.

def custom_save(filepath, *args, **kwargs):
    """ Overwrite save function to save the two sub-models """
    global encoder, decoder

    # fix name
    path, ext = os.path.splitext(filepath)

    # save encoder/decoder separately
    encoder.save(path + '-encoder.h5', *args, **kwargs)
    decoder.save(path + '-decoder.h5', *args, **kwargs)

auto_encoder = Model(auto_input, decoded)
setattr(auto_encoder, 'save', custom_save)

Make sure to set the save function BEFORE fit.

User contributions licensed under: CC BY-SA
4 People found this is helpful
Advertisement