获得Keras模型的一部分

时间:2018-11-19 21:33:08

标签: python tensorflow keras autoencoder

我有一个AutoEncoder的模型,如下所示:

height, width = 28, 28

input_img = Input(shape=(height * width,))
encoding_dim = height * width//256

x = Dense(height * width, activation='relu')(input_img)

encoded1 = Dense(height * width//2, activation='relu')(x)
encoded2 = Dense(height * width//8, activation='relu')(encoded1)

y = Dense(encoding_dim, activation='relu')(encoded2)

decoded2 = Dense(height * width//8, activation='relu')(y)
decoded1 = Dense(height * width//2, activation='relu')(decoded2)

z = Dense(height * width, activation='sigmoid')(decoded1)
autoencoder = Model(input_img, z)

#encoder is the model of the autoencoder slice in the middle 
encoder = Model(input_img, y)
decoder = Model(y, z)
print(encoder)
print(decoder)

使用上面的代码检索编码器部分,但是使用上面添加的代码无法获得解码器部分:

我收到以下错误:

ValueError: Graph disconnected: cannot obtain value for tensor Tensor("input_39:0", shape=(?, 784), dtype=float32) at layer "input_39". The following previous layers were accessed without issue: []

您能指导我如何获得这一部分吗?

1 个答案:

答案 0 :(得分:1)

decoder模型需要具有输入层。例如,此处的decoder_input

height, width = 28, 28

# Encoder layers
input_img = Input(shape=(height * width,))
encoding_dim = height * width//256

x = Dense(height * width, activation='relu')(input_img)
encoded1 = Dense(height * width//2, activation='relu')(x)
encoded2 = Dense(height * width//8, activation='relu')(encoded1)
y = Dense(encoding_dim, activation='relu')(encoded2)

# Decoder layers
decoder_input = Input(shape=(encoding_dim,))
decoded2 = Dense(height * width//8, activation='relu')(decoder_input)
decoded1 = Dense(height * width//2, activation='relu')(decoded2)
z = Dense(height * width, activation='sigmoid')(decoded1)

# Build the encoder and decoder models
encoder = Model(input_img, y)
decoder = Model(decoder_input, z)

# Finally, glue encoder and decoder together by feeding the encoder 
# output to the decoder
autoencoder = Model(input_img, decoder(y))