【发布时间】:2018-10-15 11:10:34
【问题描述】:
这个问题类似于Keras replacing input layer。
我有一个分类器网络和一个自动编码器网络,我想使用自动编码器的输出(即编码 + 解码,作为预处理步骤)作为分类器的输入 - 但在分类器已经接受常规训练之后数据。
分类网络是用这样的函数式API构建的(基于this example):
clf_input = Input(shape=(28,28,1))
clf_layer = Conv2D(...)(clf_input)
clf_layer = MaxPooling2D(...)(clf_layer)
...
clf_output = Dense(num_classes, activation='softmax')(clf_layer)
model = Model(clf_input, clf_output)
model.compile(...)
model.fit(...)
还有像这样的自动编码器(基于this example):
ae_input = Input(shape=(28,28,1))
x = Conv2D(...)(ae_input)
x = MaxPooling2D(...)(x)
...
encoded = MaxPooling2D(...)(x)
x = Conv2d(...)(encoded)
x = UpSampling2D(...)(x)
...
decoded = Conv2D(...)(x)
autoencoder = Model(ae_input, decoded)
autoencoder.compile(...)
autoencoder.fit(...)
我可以像这样连接两个模型(我仍然需要原始模型,因此需要复制):
model_copy = keras.models.clone_model(model)
model_copy.set_weights(model.get_weights())
# remove original input layer
model_copy.layers.pop(0)
# set the new input
new_clf_output = model_copy(decoded)
# get the stacked model
stacked_model = Model(ae_input, new_clf_output)
stacked_model.compile(...)
当我想要做的只是将模型应用于新的测试数据时,这很有效,但它会在这样的情况下出现错误:
for layer in stacked_model.layers:
print layer.get_config()
它到达自动编码器的末尾,但随后在分类器模型获取其输入的位置出现 KeyError 失败。此外,当使用keras.utils.plot_model 绘制模型时,我得到了这个:
您可以在其中看到自动编码器层,但最后,不是分类器模型中的各个层,而是一个块中只有完整的模型。
有没有办法连接两个模型,这样新的堆叠模型实际上是由所有单独的层组成的?
【问题讨论】:
标签: python tensorflow deep-learning keras