Keras变分自动编码器示例 - 潜在输入的使用

时间:2018-05-29 18:15:40

标签: python keras autoencoder

我是Keras的新手,并且在官方github的变量自动编码器示例中一直在努力理解变量z的用法。我不明白为什么不使用z而不是变量latent_inputs。我运行代码并且似乎有效,但我不明白是否在幕后使用z以及Keras中负责它的机制是什么。 以下是相关的代码段:

# VAE model = encoder + decoder
# build encoder model
inputs = Input(shape=input_shape, name='encoder_input')
x = Dense(intermediate_dim, activation='relu')(inputs)
z_mean = Dense(latent_dim, name='z_mean')(x)
z_log_var = Dense(latent_dim, name='z_log_var')(x)

# use reparameterization trick to push the sampling out as input
# note that "output_shape" isn't necessary with the TensorFlow backend
z = Lambda(sampling, output_shape=(latent_dim,), name='z')([z_mean, z_log_var])

# instantiate encoder model
encoder = Model(inputs, [z_mean, z_log_var, z], name='encoder')
encoder.summary()
plot_model(encoder, to_file='vae_mlp_encoder.png', show_shapes=True)

# build decoder model
latent_inputs = Input(shape=(latent_dim,), name='z_sampling')
x = Dense(intermediate_dim, activation='relu')(latent_inputs)
outputs = Dense(original_dim, activation='sigmoid')(x)

# instantiate decoder model
decoder = Model(latent_inputs, outputs, name='decoder')
decoder.summary()
plot_model(decoder, to_file='vae_mlp_decoder.png', show_shapes=True)

# instantiate VAE model
outputs = decoder(encoder(inputs)[2])
vae = Model(inputs, outputs, name='vae_mlp')

2 个答案:

答案 0 :(得分:3)

您的encoder被定义为获取输入inputs并提供输出[z_mean, z_log_var, z]的模型。然后,您可以单独定义解码器以获取一些输入,此处称为latent_inputs,输出outputs。最后,您的整体模型在以下行中定义:

outputs = decoder(encoder(inputs)[2])

这意味着您将在encoder上运行inputs,产生[z_mean, z_log_var, z],然后传递第三个元素(称为result[2])作为decoder的输入参数。换句话说,当您实施网络时,您将latent_inputs设置为等于编码器的第三个输出,或[z_mean, z_log_var, z][2] = z。您可以将其视为(可能不是有效代码):

encoder_outputs = encoder(inputs)  # [z_mean, z_log_var, z]
outputs = decoder(latent_inputs=encoder_outputs[2])  # latent_inputs = z

答案 1 :(得分:1)

它们只是单独定义编码器和解码器,因此它们可以单独使用:

  • 鉴于某些inputsencoder计算其潜在向量/低位表示z_mean, z_log_var, z(您可以单独使用encoder例如存储低维度表示,或为了便于比较)。

  • 鉴于这种低维表示latent_inputsdecoder会返回已解码的信息outputs(例如,如果您需要重复使用存储的较低表示)。

要训练/使用完整的VAE,这两种操作都可以按照实际操作方式进行链接:outputs = decoder(encoder(inputs)[2]) latent_inputs decoder接收z输出encoder)。

相关问题