【问题标题】:How to split autoencoder model to encoder and decoder in Keras?如何在 Keras 中将自动编码器模型拆分为编码器和解码器?
【发布时间】:2019-09-13 10:18:18
【问题描述】:

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

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

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

    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 replacing input layer

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

【问题讨论】:

    标签: python tensorflow keras conv-neural-network


    【解决方案1】:

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

    代码如下:

        # 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())
    

    【讨论】:

      猜你喜欢
      • 2019-07-22
      • 1970-01-01
      • 2019-01-05
      • 2019-06-14
      • 2021-08-22
      • 2019-06-29
      • 2019-05-19
      • 2017-10-22
      • 2020-09-26
      相关资源
      最近更新 更多