Autoencoders in Machine Learning
Last Updated :
01 Mar, 2025
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.

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:
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:
- 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.
- 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.
- 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.
Similar Reads
Deep Learning Tutorial
Deep Learning tutorial covers the basics and more advanced topics, making it perfect for beginners and those with experience. Whether you're just starting or looking to expand your knowledge, this guide makes it easy to learn about the different technologies of Deep Learning.Deep Learning is a branc
5 min read
Introduction to Deep Learning
Artificial Neural Network
Introduction to Convolution Neural Network
Introduction to Convolution Neural Network
Convolutional Neural Network (CNN) is an advanced version of artificial neural networks (ANNs), primarily designed to extract features from grid-like matrix datasets. This is particularly useful for visual datasets such as images or videos, where data patterns play a crucial role. CNNs are widely us
8 min read
Digital Image Processing Basics
Digital Image Processing means processing digital image by means of a digital computer. We can also say that it is a use of computer algorithms, in order to get enhanced image either to extract some useful information. Digital image processing is the use of algorithms and mathematical models to proc
7 min read
Difference between Image Processing and Computer Vision
Image processing and Computer Vision both are very exciting field of Computer Science. Computer Vision: In Computer Vision, computers or machines are made to gain high-level understanding from the input digital images or videos with the purpose of automating tasks that the human visual system can do
2 min read
CNN | Introduction to Pooling Layer
Pooling layer is used in CNNs to reduce the spatial dimensions (width and height) of the input feature maps while retaining the most important information. It involves sliding a two-dimensional filter over each channel of a feature map and summarizing the features within the region covered by the fi
5 min read
CIFAR-10 Image Classification in TensorFlow
Prerequisites:Image ClassificationConvolution Neural Networks including basic pooling, convolution layers with normalization in neural networks, and dropout.Data Augmentation.Neural Networks.Numpy arrays.In this article, we are going to discuss how to classify images using TensorFlow. Image Classifi
8 min read
Implementation of a CNN based Image Classifier using PyTorch
Introduction: Introduced in the 1980s by Yann LeCun, Convolution Neural Networks(also called CNNs or ConvNets) have come a long way. From being employed for simple digit classification tasks, CNN-based architectures are being used very profoundly over much Deep Learning and Computer Vision-related t
9 min read
Convolutional Neural Network (CNN) Architectures
Convolutional Neural Network(CNN) is a neural network architecture in Deep Learning, used to recognize the pattern from structured arrays. However, over many years, CNN architectures have evolved. Many variants of the fundamental CNN Architecture This been developed, leading to amazing advances in t
11 min read
Object Detection vs Object Recognition vs Image Segmentation
Object Recognition: Object recognition is the technique of identifying the object present in images and videos. It is one of the most important applications of machine learning and deep learning. The goal of this field is to teach machines to understand (recognize) the content of an image just like
5 min read
YOLO v2 - Object Detection
In terms of speed, YOLO is one of the best models in object recognition, able to recognize objects and process frames at the rate up to 150 FPS for small networks. However, In terms of accuracy mAP, YOLO was not the state of the art model but has fairly good Mean average Precision (mAP) of 63% when
7 min read
Recurrent Neural Network
Natural Language Processing (NLP) Tutorial
Natural Language Processing (NLP) is the branch of Artificial Intelligence (AI) that gives the ability to machine understand and process human languages. Human languages can be in the form of text or audio format.Applications of NLPThe applications of Natural Language Processing are as follows:Voice
5 min read
Introduction to NLTK: Tokenization, Stemming, Lemmatization, POS Tagging
Natural Language Toolkit (NLTK) is one of the largest Python libraries for performing various Natural Language Processing tasks. From rudimentary tasks such as text pre-processing to tasks like vectorized representation of text - NLTK's API has covered everything. In this article, we will accustom o
5 min read
Word Embeddings in NLP
Word Embeddings are numeric representations of words in a lower-dimensional space, capturing semantic and syntactic information. They play a vital role in Natural Language Processing (NLP) tasks. This article explores traditional and neural approaches, such as TF-IDF, Word2Vec, and GloVe, offering i
15+ min read
Introduction to Recurrent Neural Networks
Recurrent Neural Networks (RNNs) differ from regular neural networks in how they process information. While standard neural networks pass information in one direction i.e from input to output, RNNs feed information back into the network at each step.Imagine reading a sentence and you try to predict
10 min read
Recurrent Neural Networks Explanation
Today, different Machine Learning techniques are used to handle different types of data. One of the most difficult types of data to handle and the forecast is sequential data. Sequential data is different from other types of data in the sense that while all the features of a typical dataset can be a
8 min read
Sentiment Analysis with an Recurrent Neural Networks (RNN)
Recurrent Neural Networks (RNNs) excel in sequence tasks such as sentiment analysis due to their ability to capture context from sequential data. In this article we will be apply RNNs to analyze the sentiment of customer reviews from Swiggy food delivery platform. The goal is to classify reviews as
3 min read
Short term Memory
In the wider community of neurologists and those who are researching the brain, It is agreed that two temporarily distinct processes contribute to the acquisition and expression of brain functions. These variations can result in long-lasting alterations in neuron operations, for instance through act
5 min read
What is LSTM - Long Short Term Memory?
Long Short-Term Memory (LSTM) is an enhanced version of the Recurrent Neural Network (RNN) designed by Hochreiter & Schmidhuber. LSTMs can capture long-term dependencies in sequential data making them ideal for tasks like language translation, speech recognition and time series forecasting. Unli
7 min read
Long Short Term Memory Networks Explanation
Prerequisites: Recurrent Neural Networks To solve the problem of Vanishing and Exploding Gradients in a Deep Recurrent Neural Network, many variations were developed. One of the most famous of them is the Long Short Term Memory Network(LSTM). In concept, an LSTM recurrent unit tries to "remember" al
7 min read
LSTM - Derivation of Back propagation through time
Long Short-Term Memory (LSTM) are a type of neural network designed to handle long-term dependencies by handling the vanishing gradient problem. One of the fundamental techniques used to train LSTMs is Backpropagation Through Time (BPTT) where we have sequential data. In this article we summarize ho
4 min read
Text Generation using Recurrent Long Short Term Memory Network
LSTMs are a type of neural network that are well-suited for tasks involving sequential data such as text generation. They are particularly useful because they can remember long-term dependencies in the data which is crucial when dealing with text that often has context that spans over multiple words
5 min read