Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/tensorflow/5.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Python 在Keras中如何将自动编码器模型拆分为编码器和解码器?_Python_Tensorflow_Keras_Conv Neural Network - Fatal编程技术网

Python 在Keras中如何将自动编码器模型拆分为编码器和解码器?

Python 在Keras中如何将自动编码器模型拆分为编码器和解码器?,python,tensorflow,keras,conv-neural-network,Python,Tensorflow,Keras,Conv Neural Network,我已经训练了一个自动编码器,并使用keras内置的save()方法保存了它。现在我想把它分成两部分:编码器和解码器。通过使用旧模型创建新模型,我可以成功加载模型并获得编码器部件: encoder_model = keras.models.Model(inputs=self.model.input, outputs=self.model.get_layer(layer_of_activations).get_output_at(0)) 然而,如果我尝试用解码器做另一件事,我就做不到。我尝试了

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

encoder_model = keras.models.Model(inputs=self.model.input, 
 outputs=self.model.get_layer(layer_of_activations).get_output_at(0))
然而,如果我尝试用解码器做另一件事,我就做不到。我尝试了各种方法,但没有一种是正确的。然后我在这里发现了一个类似的问题(),并尝试使用下面的代码使用此方法:

    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
我假设这是因为在弹出原始层后,模型的输入维度没有更新,这在这个问题的第一个答案,第二个注释中有所说明:


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

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

代码如下:

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