保存Autoencoder的编码器模型

时间:2018-06-06 03:16:35

标签: python keras autoencoder

我使用ModelCheckpoint保存最佳自动编码器模型,如下所示:

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)

但是,如果保存最好的自动编码器模型,我怎样才能保存编码器模型?所以我可以重用下面的编码器模型。

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

或者是否有将编码器与自动编码器模型分开的替代方法?

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

谢谢,

1 个答案:

答案 0 :(得分:1)

您可以编写小型自定义ModelCheckpoint类来替换应保存的模型:

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