The Wayback Machine - https://web.archive.org/web/20241120210204/https://www.geeksforgeeks.org/implementing-an-autoencoder-in-pytorch/
Open In App

Implementing an Autoencoder in PyTorch

Last Updated : 07 Jul, 2022
Summarize
Comments
Improve
Suggest changes
Like Article
Like
Save
Share
Report
News Follow

Autoencoders are a type of neural network which generates an “n-layer” coding of the given input and attempts to reconstruct the input using the code generated. This Neural Network architecture is divided into the encoder structure, the decoder structure, and the latent space, also known as the “bottleneck”. To learn the data representations of the input, the network is trained using Unsupervised data. These compressed, data representations go through a decoding process wherein which the input is reconstructed. An autoencoder is a regression task that models an identity function.

Encoder Structure

This structure comprises a conventional, feed-forward neural network that is structured to predict the latent view representation of the input data. It is given by:

h_z = f_e(g_e(x_i))

Where g_e      represents the hidden layer 1,  f_e      represents the hidden layer 2, x_i      represents the input of the autoencoder, and h represents the low-dimensional, data space of the input

Decoder Structure

This structure comprises a feed-forward neural network but the dimension of the data increases in the order of the encoder layer for predicting the input. It is given by:

\bar x = g_d(f_d(h_z))

Where f_d      represents the hidden layer 1, g_d      represents the hidden layer 2, h_z      represents the low-dimensional, data space generated by the Encoder Structure and \bar x      represents the reconstructed input.

Latent Space Structure

This is the data representation or the low-level, compressed representation of the model’s input. The decoder structure uses this low-dimensional form of data to reconstruct the input. It is represented by h_z

Autoencoder Architecture

In the above figure, the top three layers represent the Encoder Block while the bottom three layers represent the Decoder Block. The latent state space is at the middle of the architecture R^1     . Autoencoders are used for image compression, feature extraction, dimensionality reduction, etc. Let’s now see the implementation.

Modules Needed

  • torch: This python package provides high-level tensor computation and deep neural networks built on autograd system.
pip install torch
  • torchvision: This module consists of a wide range of databases, image architectures, and transformations for computer vision
pip install torchvision

Implementation of Autoencoder in Pytorch

Step 1: Importing Modules

We will use the torch.optim and the torch.nn module from the torch package and datasets & transforms from torchvision package. In this article, we will be using the popular MNIST dataset comprising grayscale images of handwritten single digits between 0 and 9.

Python3

import torch
from torchvision import datasets
from torchvision import transforms
import matplotlib.pyplot as plt

                    

Step 2: Loading the Dataset

This snippet loads the MNIST dataset into loader using DataLoader module. The dataset is downloaded and transformed into image tensors. Using the DataLoader module, the tensors are loaded and ready to be used. The dataset is loaded with Shuffling enabled and a batch size of 64.

Python3

# Transforms images to a PyTorch Tensor
tensor_transform = transforms.ToTensor()
 
# Download the MNIST Dataset
dataset = datasets.MNIST(root = "./data",
                         train = True,
                         download = True,
                         transform = tensor_transform)
 
# DataLoader is used to load the dataset
# for training
loader = torch.utils.data.DataLoader(dataset = dataset,
                                     batch_size = 32,
                                     shuffle = True)

                    

Step 3: Create Autoencoder Class

In this coding snippet, the encoder section reduces the dimensionality of the data sequentially as given by:

28*28 = 784 ==> 128 ==> 64 ==> 36 ==> 18 ==> 9

Where the number of input nodes is 784 that are coded into 9 nodes in the latent space. Whereas, in the decoder section, the dimensionality of the data is linearly increased to the original input size, in order to reconstruct the input.

9 ==> 18 ==> 36 ==> 64 ==> 128 ==> 784 ==> 28*28 = 784

Where the input is the 9-node latent space representation and the output is the 28*28 reconstructed input.

The encoder starts with 28*28 nodes in a Linear layer followed by a ReLU layer, and it goes on until the dimensionality is reduced to 9 nodes. The decryptor uses these 9 data representations to bring back the original image by using the inverse of the encoder architecture. The decryptor architecture uses a Sigmoid Layer to range the values between 0 and 1 only.

Python3

# Creating a PyTorch class
# 28*28 ==> 9 ==> 28*28
class AE(torch.nn.Module):
    def __init__(self):
        super().__init__()
         
        # Building an linear encoder with Linear
        # layer followed by Relu activation function
        # 784 ==> 9
        self.encoder = torch.nn.Sequential(
            torch.nn.Linear(28 * 28, 128),
            torch.nn.ReLU(),
            torch.nn.Linear(128, 64),
            torch.nn.ReLU(),
            torch.nn.Linear(64, 36),
            torch.nn.ReLU(),
            torch.nn.Linear(36, 18),
            torch.nn.ReLU(),
            torch.nn.Linear(18, 9)
        )
         
        # Building an linear decoder with Linear
        # layer followed by Relu activation function
        # The Sigmoid activation function
        # outputs the value between 0 and 1
        # 9 ==> 784
        self.decoder = torch.nn.Sequential(
            torch.nn.Linear(9, 18),
            torch.nn.ReLU(),
            torch.nn.Linear(18, 36),
            torch.nn.ReLU(),
            torch.nn.Linear(36, 64),
            torch.nn.ReLU(),
            torch.nn.Linear(64, 128),
            torch.nn.ReLU(),
            torch.nn.Linear(128, 28 * 28),
            torch.nn.Sigmoid()
        )
 
    def forward(self, x):
        encoded = self.encoder(x)
        decoded = self.decoder(encoded)
        return decoded

                    

Step 4: Initializing Model

We validate the model using the Mean Squared Error function, and we use an Adam Optimizer with a learning rate of 0.1 and weight decay of 10^{-8}

Python3

# Model Initialization
model = AE()
 
# Validation using MSE Loss function
loss_function = torch.nn.MSELoss()
 
# Using an Adam Optimizer with lr = 0.1
optimizer = torch.optim.Adam(model.parameters(),
                             lr = 1e-1,
                             weight_decay = 1e-8)

                    

Step 5: Create Output Generation

The output against each epoch is computed by passing as a parameter into the Model() class and the final tensor is stored in an output list. The image into (-1, 784) and is passed as a parameter to the Autoencoder class, which in turn returns a reconstructed image. The loss function is calculated using MSELoss function and plotted. In the optimizer, the initial gradient values are made to zero using zero_grad(). loss.backward() computes the grad values and stored. Using the step() function, the optimizer is updated.

The original image and the reconstructed image from the outputs list are detached and transformed into a NumPy Array for plotting the images.

Note: This snippet takes 15 to 20 mins to execute, depending on the processor type. Initialize epoch = 1, for quick results. Use a GPU/TPU runtime for faster computations.

Python3

epochs = 20
outputs = []
losses = []
for epoch in range(epochs):
    for (image, _) in loader:
       
      # Reshaping the image to (-1, 784)
      image = image.reshape(-1, 28*28)
       
      # Output of Autoencoder
      reconstructed = model(image)
       
      # Calculating the loss function
      loss = loss_function(reconstructed, image)
       
      # The gradients are set to zero,
      # the gradient is computed and stored.
      # .step() performs parameter update
      optimizer.zero_grad()
      loss.backward()
      optimizer.step()
       
      # Storing the losses in a list for plotting
      losses.append(loss)
    outputs.append((epochs, image, reconstructed))
 
# Defining the Plot Style
plt.style.use('fivethirtyeight')
plt.xlabel('Iterations')
plt.ylabel('Loss')
 
# Plotting the last 100 values
plt.plot(losses[-100:])

                    

Output:

Loss function graph

Step 6: Input/Reconstructed Input to/from Autoencoder

The first input image array and the first reconstructed input image array have been plotted using plt.imshow().

Python3

for i, item in enumerate(image):
   
  # Reshape the array for plotting
  item = item.reshape(-1, 28, 28)
  plt.imshow(item[0])
 
for i, item in enumerate(reconstructed):
  item = item.reshape(-1, 28, 28)
  plt.imshow(item[0])

                    

Output:

Sample Plot 1: Input image(left) and reconstructed input(right)

Sample Plot 2: Input image(left) and reconstructed input(right)

Although the rebuilt pictures appear to be adequate, they are extremely grainy. To enhance this outcome, extra layers and/or neurons may be added, or the autoencoder model could be built on convolutions neural network architecture. For dimensionality reduction, autoencoders are quite beneficial. However, it might also be used for data denoising and understanding a dataset’s spread.



Previous Article
Next Article

Similar Reads

Implement Deep Autoencoder in PyTorch for Image Reconstruction
Since the availability of staggering amounts of data on the internet, researchers and scientists from industry and academia keep trying to develop more efficient and reliable data transfer modes than the current state-of-the-art methods. Autoencoders are one of the key elements found in recent times used for such a task with their simple and intuit
8 min read
Implement Convolutional Autoencoder in PyTorch with CUDA
Autoencoders are a type of neural network architecture used for unsupervised learning tasks such as data compression, dimensionality reduction, and data denoising. The architecture consists of two main components: an encoder and a decoder. The encoder portion of the network compresses the input data into a lower-dimensional representation, while th
4 min read
ML | AutoEncoder with TensorFlow 2.0
This tutorial demonstrates how to generate images of handwritten digits using graph mode execution in TensorFlow 2.0 by training an Autoencoder. An AutoEncoder is a data compression and decompression algorithm implemented with Neural Networks and/or Convolutional Neural Networks. the data is compressed to a bottleneck that is of a lower dimension t
4 min read
How is Autoencoder different from PCA
In this article, we are going to see how is Autoencoder different from Principal Component Analysis (PCA). Role of Dimensionality Reduction in MLWe often come into the curse of dimensionality issues in machine learning projects, when the amount of data records is not a significant component of the number of features. This often causes issues since
3 min read
Selection of GAN vs Adversarial Autoencoder models
In this article, we are going to see the selection of GAN vs Adversarial Autoencoder models. Generative Adversarial Network (GAN)The Generative Adversarial Network, or GAN, is one of the most prominent deep generative modeling methodologies right now. The primary distinction between GAN and VAE is that GAN seeks to match the pixel level distributio
6 min read
Convolutional Variational Autoencoder in Tensorflow
In the age of Generative AI, the creation of generative models is very crucial for learning and synthesizing complex data distributions within the dataset. By incorporating convolutional layers with Variational Autoencoders, we can create a such kind of generative model. In this article, we will discuss about CVAE and implement it. Convolutional Va
10 min read
Contractive Autoencoder (CAE)
In this article, we will learn about Contractive Autoencoders which come in very handy while extracting features from the images, and how normal autoencoders have been improved to create Contractive Autoencoders. What is Contarctive AutoEncoder?Contractive Autoencoder was proposed by researchers at the University of Toronto in 2011 in the paper Con
5 min read
Undercomplete Autoencoder
In the expansive field of machine learning, undercomplete autoencoders have carved out a niche as powerful tools for unsupervised learning, especially in dimensionality reduction and feature extraction. These specialized types of neural networks are designed to compress input data into a lower-dimensional space and then reconstruct it back to its o
7 min read
Perceptual Autoencoder: Enhancing Image Reconstruction with Deep Learning
In recent years, autoencoders have emerged as powerful tools in unsupervised learning, especially in image compression and reconstruction. The Perceptual Autoencoder is a specialized type of autoencoder that takes image reconstruction to the next level by optimizing for pixel-wise accuracy and perceptual similarity. This method ensures that reconst
15 min read
Implementing Recurrent Neural Networks in PyTorch
Recurrent Neural Networks (RNNs) are a class of neural networks that are particularly effective for sequential data. Unlike traditional feedforward neural networks, RNNs have connections that form directed cycles, allowing them to maintain a hidden state that can capture information from previous inputs. This makes them suitable for tasks such as t
8 min read
PyTorch vs PyTorch Lightning
The PyTorch research team at Facebook AI Research (FAIR) introduced PyTorch Lightning to address these challenges and provide a more organized and standardized approach. In this article, we will see the major differences between PyTorch Lightning and Pytorch. Table of Content PytorchPytorch Lightning: Advanced Framework of PytorchPytorch vs Pytorch
9 min read
How to disable GPU in PyTorch (force Pytorch to use CPU instead of GPU)?
PyTorch is a deep learning framework that offers GPU acceleration. This enables the users to utilize the GPU's processing power. The main goal is to accelerate the training and interference processes of deep learning models. PyTorch automatically utilizes the GPU for operations and this leads to quicker computation times. Using the GPU for PyTorch
5 min read
Implementing Apriori algorithm in Python
Prerequisites: Apriori AlgorithmApriori Algorithm is a Machine Learning algorithm which is used to gain insight into the structured relationships between different items involved. The most prominent practical application of the algorithm is to recommend products based on the products already present in the user's cart. Walmart especially has made g
4 min read
Implementing Deep Q-Learning using Tensorflow
Prerequisites: Deep Q-Learning This article will demonstrate how to do reinforcement learning on a larger environment than previously demonstrated. We will be implementing Deep Q-Learning technique using Tensorflow. Note: A graphics rendering library is required for the following demonstration. For Windows operating system, PyOpenGl is suggested wh
4 min read
Implementing PCA in Python with scikit-learn
In this article, we will learn about PCA (Principal Component Analysis) in Python with scikit-learn. Let's start our learning step by step. WHY PCA? When there are many input attributes, it is difficult to visualize the data. There is a very famous term ‘Curse of dimensionality in the machine learning domain.Basically, it refers to the fact that a
4 min read
Implementing Rich getting Richer phenomenon using Barabasi Albert Model in Python
Prerequisite- Introduction to Social Networks, Barabasi Albert Graph In social networks, there is a phenomenon called Rich getting Richer also known as Preferential Attachment. In Preferential Attachment, a person who is already rich gets more and more and a person who is having less gets less. This is called the Rich getting Richer phenomena or Pr
4 min read
Implementing Neural Networks Using TensorFlow
Deep learning has been on the rise in this decade and its applications are so wide-ranging and amazing that it's almost hard to believe that it's been only a few years in its advancements. And at the core of deep learning lies a basic "unit" that governs its architecture, yes, It's neural networks. A neural network architecture comprises a number o
8 min read
Implementing SVM and Kernel SVM with Python's Scikit-Learn
In this article we will implement a classification model using Scikit learn implementation for SVM model in Python. Then we will try to understand what is a kernel and how it can helps us to achieve better performance by learning non-linear boundaries in the dataset. What is a SVM algorithm? Support vector machines (SVMs) are a type of supervised l
6 min read
Implementing Models of Artificial Neural Network
1. McCulloch-Pitts Model of Neuron The McCulloch-Pitts neural model, which was the earliest ANN model, has only two types of inputs — Excitatory and Inhibitory. The excitatory inputs have weights of positive magnitude and the inhibitory weights have weights of negative magnitude. The inputs of the McCulloch-Pitts neuron could be either 0 or 1. It h
7 min read
Implementing DBSCAN algorithm using Sklearn
Prerequisites: DBSCAN Algorithm Density Based Spatial Clustering of Applications with Noise(DBCSAN) is a clustering algorithm which was proposed in 1996. In 2014, the algorithm was awarded the 'Test of Time' award at the leading Data Mining conference, KDD. Dataset - Credit Card Step 1: Importing the required libraries import numpy as np import pan
3 min read
ML | Implementing L1 and L2 regularization using Sklearn
Prerequisites: L2 and L1 regularizationThis article aims to implement the L2 and L1 regularization for Linear regression using the Ridge and Lasso modules of the Sklearn library of Python. Dataset - House prices dataset.Step 1: Importing the required libraries C/C++ Code import pandas as pd import numpy as np import matplotlib.pyplot as plt from sk
3 min read
Implementing Agglomerative Clustering using Sklearn
Prerequisites: Agglomerative Clustering Agglomerative Clustering is one of the most common hierarchical clustering techniques. Dataset - Credit Card Dataset. Assumption: The clustering technique assumes that each data point is similar enough to the other data points that the data at the starting can be assumed to be clustered in 1 cluster. Step 1:
3 min read
ML | OPTICS Clustering Implementing using Sklearn
Prerequisites: OPTICS Clustering This article will demonstrate how to implement OPTICS Clustering technique using Sklearn in Python. The dataset used for the demonstration is the Mall Customer Segmentation Data which can be downloaded from Kaggle. Step 1: Importing the required libraries OPTICS (Ordering Points To Identify the Clustering Structure)
5 min read
MLOps Pipeline: Implementing Efficient Machine Learning Operations
In the rapidly evolving world of artificial intelligence and machine learning, the need for efficient and scalable operations has never been more critical. Enter MLOps, a set of practices that combines machine learning (ML) and operations (Ops) to automate and streamline the end-to-end ML lifecycle. This article delves into the intricacies of the M
8 min read
Reinforcement Learning in Python: Implementing SARSA Agent in Taxi Environment
SARSA (State-Action-Reward-State-Action) is an on-policy reinforcement learning algorithm that updates its policy based on the current state-action pair, the reward received, the next state, and the next action chosen by the current policy. In this article, we will implement SARSA in Gymnasium's Taxi-v3 environment, walking through the setup, agent
8 min read
Implementing Dropout in TensorFlow
In deep learning, overfitting is a common challenge. Overfitting occurs when a model learns the noise in the training data rather than the actual patterns, leading to poor generalization on new data. One effective technique to combat overfitting is dropout. This article delves into the concept of dropout and provides a practical guide on how to imp
7 min read
Building and Implementing Decision Tree Classifiers with Scikit-Learn: A Comprehensive Guide
A decision tree classifier is a well-liked and adaptable machine learning approach for classification applications. It creates a model in the shape of a tree structure, with each internal node standing in for a "decision" based on a feature, each branch for the decision's result, and each leaf node for a regression value or class label. Decision tr
10 min read
Implementing the AdaBoost Algorithm From Scratch
In this article, we will learn about the AdaBoost classifier and its practical implementation over a dataset.AdaBoost algorithm falls under ensemble boosting techniques, as we will discuss it combines multiple models to produce more accurate results and this is done in two phases: Multiple weak learners are allowed to learn on training dataCombinin
6 min read
Implementing Generalized Least Squares (GLS) in Python
Generalized Least Squares (GLS) is a statistical technique used to estimate the unknown parameters in a linear regression model. It extends the Ordinary Least Squares (OLS) method by addressing situations where the assumptions of OLS are violated, specifically when there is heteroscedasticity or autocorrelation in the error terms. GLS is crucial in
6 min read
Implementing CART (Classification And Regression Tree) in Python
Classification and Regression Trees (CART) are a type of decision tree algorithm used in machine learning and statistics for predictive modeling. CART is versatile, used for both classification (predicting categorical outcomes) and regression (predicting continuous outcomes) tasks. Here we check the CART methodology, its implementation, and its app
6 min read
three90RightbarBannerImg