python - 如何在 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
简单地遍历层并在新模型中重新创建它们是行不通的,因为我的模型不是连续的。
解决方案
我通过构建一个与原始自动编码器网络的解码器部分具有完全相同架构的新模型来解决这个问题,然后只复制权重。
这是代码:
# 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())
推荐阅读
- html - CSS页脚不粘并浮动到底部
- c# - MVVMLight C# 如何更改按钮内容
- r - 转换为纯 Markdown 时,不要在 rmarkdown 文档中呈现方程式
- python - Python 遍历产生列表的异步生成器
- python - 如何在 kaggle 中解压缩 cat-vs-dogs 数据?
- c - 将字符串文字复制到 uint32_t 数组并访问它
- react-native - 更新由管理的视图的属性“背景颜色”时出错:RNCardView - React Native
- javascript - Firebase 身份验证 - 用户注销时不会调用 onAuthStateChanged (JS)
- wordpress - WordPress Nextend 社交登录插件 Facebook 登录 - 应用验证
- java - 我怎样才能避免内循环