The Wayback Machine - https://web.archive.org/web/20250526210909/https://www.geeksforgeeks.org/auto-encoders/
Open In App

Autoencoders in Machine Learning

Last Updated : 01 Mar, 2025
Comments
Improve
Suggest changes
Like Article
Like
Report

An autoencoder is a type of artificial neural network that learns to represent data in a compressed form and then reconstructs it as closely as possible to the original input.

Autoencoders consists of two components:

  • Encoder: This compresses the input into a compact representation and capture the most relevant features.
  • Decoder: It reconstructs the input data from this compressed form to make it as similar as possible to the original input.

For example if the input is a noisy image of handwritten digits the autoencoder can learn to remove noise by compressing the image into a smaller feature set and reconstructing a cleaner version of the original image.

Autoencoders aim to minimize reconstruction error which is the difference between the input and the reconstructed output. They use loss functions such as Mean Squared Error (MSE) or Binary Cross-Entropy (BCE) and optimize through backpropagation and gradient descent. They are used in applications like image processing, anomaly detection, noise removal and feature extraction

Architecture of Autoencoder in Deep Learning

The architecture of an autoencoder consists of three main components: the Encoder, the Bottleneck (Latent Space) and the Decoder. Let's deep dive into each part to understand how they work together.

Autoencoder in Deep Learning

1. Encoder

The encoder is the part of the network that takes the input data and compresses it into a smaller lower-dimensional representation.

  • Input Layer: This is where the original data enters the network e.g., an image or a set of features.
  • Hidden Layers: These layers apply transformations to the input data. The encoder's goal is to extract essential features and reduce the data's dimensionality.
  • Output of Encoder (Latent Space): The encoder outputs a compressed version of the data often called the latent representation or encoding. This is a condensed version of the input retaining only the important features.

2. Bottleneck (Latent Space)

The bottleneck is the smallest layer of the network where the data is represented in its most compressed form. It’s often referred to as the latent space or code.

  • This layer contains a reduced set of features representing the most important information from the input.
  • The idea is that through this compression the network learns the key patterns and structures of the input data.

3. Decoder

The decoder is responsible for taking the compressed representation from the latent space and reconstructing it back into the original data form.

  • Hidden Layers: The decoder uses a series of layers to gradually expand the compressed data back to the original input’s dimensions.
  • Output Layer: This layer produces the reconstructed data and aim to closely resemble the input data.

Loss Function in Autoencoder Training

During training an autoencoder aims to minimize the reconstruction loss which measures the difference between the original input and the reconstructed output. The choice of loss function depends on the type of data:

  • Mean Squared Error (MSE): This is commonly used for continuous data. It measures the average squared differences between the input and the reconstructed data.
  • Binary Cross-Entropy: Used for binary data (0 or 1 values). It calculates the difference in probability between the original and reconstructed output.

The network adjusts its weights to minimize this reconstruction loss learning to extract and retain only the most important features of the input data which are then stored in the latent space (bottleneck layer).

Autoencoder Efficient Representations

Constraining an autoencoders makes it learn and show efficient representation. Constraining an autoencoder means that the network learns meaningful, compact and useful features from the input data. After the network is trained only the encoder part is used to encode similar data for future tasks. Several techniques can be employed to achieve this goal:

  • Keep Small Hidden Layers: By making each hidden layer as small as possible the network is forced to learn only the most important features of the data. A smaller layer size means less redundancy and efficient encoding.
  • Regularization: Regularization methods like L1 or L2 regularization add a penalty terms to the loss function, preventing the network from overfitting. This ensures that the learned representations are more general and useful by discouraging excessively large weights.
  • Denoising: In denoising autoencoders random noise is added to the input data during training. The network is then forced to remove this noise during reconstruction which helps it focus on the core, noise-free features of the data and makes the model more robust.
  • Tuning the Activation Functions: Modifying the activation functions can encourage sparsity in the hidden layer, where only a few neurons are active at a time. This sparsity forces the network to learn only the most relevant features, reducing the complexity of the model and improving its efficiency.

Types of Autoencoders

Autoencoders come in several types each suited for different tasks and with unique features. Let’s understand the main types of autoencoders.

1. Denoising Autoencoder

Denoising Autoencoder is trained to work with corrupted or noisy input and learns to remove the noise and reconstruct the original, clean data. It helps the network avoid memorizing the input and forces it to learn the core features of the data instead.

2. Sparse Autoencoder

Sparse Autoencoder contains more hidden units than the input but only a few are allowed to be active at once. This property is called the sparsity of the network. The sparsity of the network can be controlled by either manually zeroing the required hidden units, tuning the activation functions or by adding a loss term to the cost function.

3. Variational Autoencoder

Variational autoencoder (VAE) makes assumptions about the probability distribution of the data and tries to learn a better approximation of it. It uses stochastic gradient descent to optimize and learn the distribution of latent variables. VAEs are often used for generating new data such as creating realistic images or text.

It assumes that the data is generated by a Directed Graphical Model and tries to learn an approximation to q_{\phi}(z|x)      to the conditional property q_{\theta}(z|x)      where \phi      and \theta      are the parameters of the encoder and the decoder respectively.

4. Convolutional Autoencoder

Convolutional autoencoder uses convolutional neural networks (CNNs) which are specifically designed for processing images. In this type of autoencoder the encoder uses convolutional layers to extract features from an image and the decoder applies deconvolution also called upsampling to reconstruct the image.

Implementation of Autoencoders

We've created an autoencoder comprising two Dense layers: an encoder responsible for condensing the images into a 64-dimensional latent vector and a decoder tasked with reconstructing the initial image based on this latent space.

Step 1: Import necessary libraries

For the implementation we are going to import matplotlib, numpy, pandas, sklearn and keras.

Python
import numpy as np
import matplotlib.pyplot as plt
import tensorflow as tf
from tensorflow import keras
from tensorflow.keras import layers, losses
from tensorflow.keras.models import Model
from keras.datasets import mnist

Step 2: Load the MNIST dataset

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

x_train = x_train.astype('float32') / 255.
x_test = x_test.astype('float32') / 255.

x_train = np.reshape(x_train, (len(x_train), 28, 28, 1))
x_test = np.reshape(x_test, (len(x_test), 28, 28, 1))

Output:

Shape of the training data: (60000, 28, 28)
Shape of the testing data: (10000, 28, 28)

Step 3: Define a basic Autoencoder

  • Simple Autoencoder class is defined.
  • Constructor initializes the autoencoder with specified latent dimensions and data shape
  • The encoder and decoder architectures is defined using Sequential model
  • The call method defines the forward pass of the autoencoder where input data is passed through the encoder to obtain encoded data and then through the decoder to obtain the decoded data.
Python
class SimpleAutoencoder(Model):
    def __init__(self, latent_dimensions):
        super(SimpleAutoencoder, self).__init__()
        self.encoder = tf.keras.Sequential([
            layers.Input(shape=(28, 28, 1)),
            layers.Flatten(),
            layers.Dense(latent_dimensions, activation='relu'),
        ])
        
        self.decoder = tf.keras.Sequential([
            layers.Dense(28 * 28, activation='sigmoid'),
            layers.Reshape((28, 28, 1))
        ])
    
    def call(self, input_data):
        encoded = self.encoder(input_data)
        decoded = self.decoder(encoded)
        return decoded

Step 4: Compiling and Fitting Autoencoder

Python
latent_dimensions = 64
autoencoder = SimpleAutoencoder(latent_dimensions)
autoencoder.compile(optimizer='adam', loss=losses.MeanSquaredError())

autoencoder.fit(x_train, x_train,
                epochs=10,
                batch_size=256,
                shuffle=True,
                validation_data=(x_test, x_test))

Output:

Screenshot-2025-02-28-141551

Step 5: Visualize original and reconstructed data

Python
encoded_imgs = autoencoder.encoder(x_test).numpy()
decoded_imgs = autoencoder.decoder(encoded_imgs).numpy()

n = 6
plt.figure(figsize=(12, 6))
for i in range(n):
    ax = plt.subplot(2, n, i + 1)
    plt.imshow(x_test[i].reshape(28, 28), cmap='gray')
    plt.title("Original")
    plt.axis('off')

    ax = plt.subplot(2, n, i + 1 + n)
    plt.imshow(decoded_imgs[i].reshape(28, 28), cmap='gray')
    plt.title("Reconstructed")
    plt.axis('off')

plt.show()

Output:

Limitations of Autoencoders

Autoencoders are useful tools but they come with some challenges:

  1. Memorizing Instead of Learning Patterns: Autoencoders can sometimes memorize the data meaning they just learn to copy the input exactly rather than uncovering the real patterns. When the model memorizes data it doesn’t perform well on new, unseen data which limits its ability to generalize.
  2. Reconstructed Data Might Not Be Perfect: Even though autoencoders aim to reconstruct the input as accurately as possible the output may not always be perfect. The reconstructed data can sometimes be blurry or distorted. This happens when the autoencoder struggles to capture all the fine details of the input especially when there's too much noise or if the model’s architecture isn’t powerful enough to handle the complexity.
  3. Requires a Large Dataset and Good Parameter Tuning: For an autoencoder to perform well it typically needs a large dataset and careful tuning of its parameters (like the size of the latent space or the learning rate). If the dataset is too small or the parameters are not well-tuned the model may fail to learn meaningful representations of the data lead to poor performance.

Next Article

Similar Reads