首页 > 解决方案 > 如何在 Keras 中将自动编码器模型拆分为编码器和解码器?

问题描述

我已经训练了一个自动编码器并使用 keras 内置的 save() 方法保存了它。现在我想把它分成两部分:编码器和解码器。我可以通过使用旧模型创建新模型来成功加载模型并获取编码器部分:

encoder_model = keras.models.Model(inputs=self.model.input, 
 outputs=self.model.get_layer(layer_of_activations).get_output_at(0))

但是,如果我尝试用解码器做替代的事情,我不能。我尝试了各种方法,但没有一个是正确的。然后我在这里发现了一个类似的问题(Keras 替换输入层)并尝试使用以下代码使用此方法:

    for i, l in enumerate(self.model.layers[0:19]):
        self.model.layers.pop(0)
    newInput = Input(batch_shape=(None, None, None, 64))
    newOutputs = self.model(newInput)
    newModel = keras.models.Model(newInput, newOutputs)

我删除的最后一层的输出形状是 (None, None, None, 64),但是这段代码会产生以下错误:

ValueError: number of input channels does not match corresponding dimension of filter, 64 != 3

我认为这是因为模型的输入尺寸在弹出原始层后没有更新,这在这个问题的第一个答案,第二条评论中有所说明:Keras replace input layer

简单地遍历层并在新模型中重新创建它们是行不通的,因为我的模型不是连续的。

标签: pythontensorflowkerasconv-neural-network

解决方案


我通过构建一个与原始自动编码器网络的解码器部分具有完全相同架构的新模型来解决这个问题,然后只复制权重。

这是代码:

    # Looping through the old model and popping the encoder part + encoded layer
    for i, l in enumerate(self.model.layers[0:19]): 
        self.model.layers.pop(0)

    # Building a clean model that is the exact same architecture as the decoder part of the autoencoder
    new_model = nb.build_decoder()

    # Looping through both models and setting the weights on the new decoder
    for i, l in enumerate(self.model.layers):
        new_model.layers[i+1].set_weights(l.get_weights())

推荐阅读