VOOZH about

URL: https://www.geeksforgeeks.org/machine-learning/variational-autoencoders/

⇱ Variational AutoEncoders - GeeksforGeeks


  • Courses
  • Tutorials
  • Interview Prep

Variational AutoEncoders

Last Updated : 16 Dec, 2025

Variational Autoencoders (VAEs) are generative models that learn a smooth, probabilistic latent space, allowing them not only to compress and reconstruct data but also to generate entirely new, realistic samples. VAEs capture the underlying structure of a dataset and produce outputs that closely resemble the original data.

  • Learns a continuous latent representation
  • Enables controlled and meaningful data generation
  • Widely used in image synthesis, anomaly detection, and representation learning

Architecture of Variational Autoencoder

👁 distributions
Variational Autoencoder

VAE is a special kind of autoencoder that can generate new data instead of just compressing and reconstructing it. It has three main parts:

1. Encoder (Understanding the Input)

The encoder takes input data like images or text and learns its key features. Instead of outputting one fixed value, it produces two vectors for each feature:

  • Mean (μ): A central value representing the data.
  • Standard Deviation (σ): It is a measure of how much the values can vary.

These two values define a range of possibilities instead of a single number.

2. Latent Space (Adding Some Randomness)

Instead of encoding the input as one fixed point it pick a random point within the range given by the mean and standard deviation. This randomness lets the model create slightly different versions of data which is useful for generating new, realistic samples.

3. Decoder (Reconstructing or Creating New Data)

The decoder takes the random sample from the latent space and tries to reconstruct the original input. Since the encoder gives a range, the decoder can produce new data that is similar but not identical to what it has seen.

Mathematics behind Variational Autoencoder

Variational autoencoder uses KL-divergence as its loss function the goal of this is to minimize the difference between a supposed distribution and original distribution of dataset.

Suppose we have a distribution and we want to generate the observation from it.  In other words we want to calculate We can do it by following way:

But, the calculation of can be difficult:

This usually makes it an intractable distribution. Hence we need to approximate to to make it a tractable distribution. To better approximate to we will minimize the KL-divergence loss which calculates how similar two distributions are:

By simplifying the above minimization problem is equivalent to the following maximization problem :

The first term represents the reconstruction likelihood and the other term ensures that our learned distribution is similar to the true prior distribution . Thus our total loss consists of two terms one is reconstruction error and other is KL divergence loss:

Implementing Variational Autoencoder

We will build a Variational Autoencoder using TensorFlow and Keras. The model will be trained on the Fashion-MNIST dataset which contains 28×28 grayscale images of clothing items. This dataset is available directly through Keras.

Step 1: Importing Libraries

First we will be importing Numpy, TensorFlow, Keras layers and Matplotlib for this implementation.

Step 2: Creating a Sampling Layer

The sampling layer acts as the bottleneck, taking the mean and standard deviation from the encoder and sampling latent vectors by adding randomness. This allows the VAE to generate varied outputs.

  • epsilon = tf.random.normal(shape=tf.shape(mean)): Generate random noise from normal distribution.
  • return mean + tf.exp(0.5 * log_var) * epsilon: Apply reparameterization trick to sample latent vector.

Step 3: Defining Encoder Block

The encoder takes input images and outputs two vectors: mean and log variance. These describe the distribution from which latent vectors are sampled.

  • x = layers.Dense(128, activation="relu")(x): Fully connected layer with 128 units and ReLU activation.
  • encoder = keras.Model(encoder_inputs, [mean, log_var, z], name="encoder"): Define encoder model from input to outputs.

Output:

👁 encoder
Summary

Step 4: Defining Decoder Block

Now we will define the architecture of decoder part of our autoencoder which takes sampled latent vectors and reconstructs the image.

  • x = layers.Dense(128, activation="relu")(latent_inputs): Dense layer to expand latent vector.
  • x = layers.Dense(28 * 28, activation="sigmoid")(x): Output layer to generate 784 pixels with values between 0 and 1.

Output:

👁 decoder
Summary

Step 5: Defining the VAE Model

Combine encoder and decoder into the VAE model and define the custom training step including reconstruction and KL-divergence losses.

  • self.loss_fn = keras.losses.BinaryCrossentropy(from_logits=False): Set reconstruction loss as binary cross-entropy.
  • with tf.GradientTape() as tape: Record operations for gradient calculation.
  • kl_loss = -0.5 * tf.reduce_mean(1 + log_var - tf.square(mean) - tf.exp(log_var)): Calculate KL divergence loss.

Step 6: Training the VAE

Load the Fashion-MNIST dataset and train the model for 10 epochs.

  • x_train = np.expand_dims(x_train, -1): Add channel dimension to training images.
  • x_test = x_test.astype("float32") / 255.0: Normalize test images.
  • x_test = np.expand_dims(x_test, -1): Add channel dimension to test images.

Output:

👁 training-output
Training

Step 7: Displaying Sampled Images

Generate new images by sampling points from the latent space and display them.

  • z_sample = np.array([[xi, yi]]): Create latent vector from grid point.
  • x_decoded = decoder.predict(z_sample): Decode latent vector to image.

Output:

👁 vae
Sampled Images

Step 8: Displaying Latent Space Clusters

Encode the test set images and plot their positions in latent space to visualize clusters.

  • mean, _, _ = encoder.predict(x_test): Encode test images to latent mean vectors.

Output:

👁 output-vae
Latent Space Clusters

We can see that our model is working fine.

You can download source code from here.

Comment
Article Tags: