We build the model as follows:
vae = Model(x, reconstructed)
Define the reconstruction loss:
Reconstruction_loss = original_dim * metrics.binary_crossentropy(x, reconstructed)
Define KL divergence:
kl_divergence_loss = - 0.5 * K.sum(1 + z_log_var - K.square(z_mean) - K.exp(z_log_var), axis=-1)
Thus, the total loss can be defined as:
total_loss = K.mean(Reconstruction_loss + kl_divergence_loss)
Add loss and compile the model:
vae.add_loss(total_loss)
vae.compile(optimizer='rmsprop')
vae.summary()
Train the model:
vae.fit(x_train,
shuffle=True,
epochs=epochs,
batch_size=batch_size,
verbose=2,
validation_data=(x_test, None))