重用中间层作为Keras中另一个模型的输入

时间:2018-09-27 10:18:45

标签: python machine-learning neural-network keras autoencoder

我正在用Keras构建5层自动编码器。我制作了从输入到输出映射的模型,这很好。我建立了另一个模型,该模型可以将输入映射到可以正常工作的潜在编码矢量。但是,我然后尝试建立一个解码模型,将潜在的编码向量映射到无效的输出。

我知道,首先我应该为构成该形状的已解码模型创建一个输入层,但是我不知道如何获取编码层数据作为已解码模型的输入,以及如何将其映射到编码矢量到最后一层。

from keras.layers import Input, Dense
from keras.models import Model
from keras.datasets import mnist
import numpy as np

(x_train, _), (x_test, _) = mnist.load_data()
(x_train, _), (x_test, _) = mnist.load_data()

# Prepare data and normalize
x_train = x_train.astype('float32') / 255.
x_test = x_test.astype('float32') / 255.
x_train = x_train.reshape(len(x_train), -1)
x_test = x_test.reshape(len(x_test), -1)

input_size = 784
hidden_size = 128
coded_size = 64

x = Input(shape=(input_size,))
hidden_1 = Dense(hidden_size, activation='relu')(x)
coded =Dense(coded_size, activation='relu')(hidden_1)
hidden_2 = Dense(hidden_size, activation='relu')(coded)
r = Dense(input_size, activation='sigmoid')(hidden_2)

autoencoder = Model(inputs=x, outputs=r)
encoder = Model(inputs=x, outputs=coded)

decoder_input = Input(shape=(coded_size,))  # should do this, but don't know how to connect it below
decoder = Model(inputs=coded, output=r)

1 个答案:

答案 0 :(得分:1)

您可以这样做:

decoder_input = Input(shape=(coded_size,))
next_input = decoder_input

# get the decoder layers and apply them consecutively
for layer in autoencoder.layers[-2:]:
    next_input = layer(next_input)

decoder = Model(inputs=decoder_input, outputs=next_input)

请注意,您的模型中没有h。我认为必须将其替换为coded