Skip to content
geeksforgeeks
  • Courses
    • DSA to Development
    • Get IBM Certification
    • Newly Launched!
      • Master Django Framework
      • Become AWS Certified
    • For Working Professionals
      • Interview 101: DSA & System Design
      • Data Science Training Program
      • JAVA Backend Development (Live)
      • DevOps Engineering (LIVE)
      • Data Structures & Algorithms in Python
    • For Students
      • Placement Preparation Course
      • Data Science (Live)
      • Data Structure & Algorithm-Self Paced (C++/JAVA)
      • Master Competitive Programming (Live)
      • Full Stack Development with React & Node JS (Live)
    • Full Stack Development
    • Data Science Program
    • All Courses
  • Tutorials
    • Data Structures & Algorithms
    • ML & Data Science
    • Interview Corner
    • Programming Languages
    • Web Development
    • CS Subjects
    • DevOps And Linux
    • School Learning
  • Practice
    • Build your AI Agent
    • GfG 160
    • Problem of the Day
    • Practice Coding Problems
    • GfG SDE Sheet
  • Contests
    • Accenture Hackathon (Ending Soon!)
    • GfG Weekly [Rated Contest]
    • Job-A-Thon Hiring Challenge
    • All Contests and Events
  • Data Science
  • Data Science Projects
  • Data Analysis
  • Data Visualization
  • Machine Learning
  • ML Projects
  • Deep Learning
  • NLP
  • Computer Vision
  • Artificial Intelligence
Open In App
Next Article:
Graph Neural Networks with PyTorch
Next article icon

How to Visualize PyTorch Neural Networks

Last Updated : 26 Aug, 2024
Comments
Improve
Suggest changes
Like Article
Like
Report

Visualizing neural networks is crucial for understanding their architecture, debugging, and optimizing models. PyTorch offers several ways to visualize both simple and complex neural networks.

In this article, we'll explore how to visualize different types of neural networks, including a simple feedforward network, a larger network with multiple layers, and a complex pre-defined network like ResNet.

Table of Content

  • Visualizing a Simple Neural Network
  • Steps to Visualize a Larger Neural Network in PyTorch
  • Visualizing a Pre-trained Model in PyTorch
  • Tips for Visualizing Complex Networks

Visualizing a Simple Neural Network

Let's start by visualizing a simple feedforward neural network. We'll define a basic model, create a dummy input, and visualize the computation graph using the torchviz library.

Before we begin, make sure you have the following prerequisites:

  • PyTorch Installed: Ensure you have PyTorch installed in your environment. You can install it using pip:
pip install torch torchvision
  • Torchviz: A package that helps in visualizing PyTorch models. Install it using pip:
pip install torchviz
  • Graphviz: A visualization package that works with Torchviz. You can install it using pip:
pip install graphviz

Step 1: Define a Simple Neural Network

First, we need to define a simple neural network. For this example, we'll create a basic feedforward neural network.

import torch
import torch.nn as nn
import torch.nn.functional as F

class SimpleNet(nn.Module):
def __init__(self):
super(SimpleNet, self).__init__()
self.fc1 = nn.Linear(784, 128)
self.fc2 = nn.Linear(128, 64)
self.fc3 = nn.Linear(64, 10)

def forward(self, x):
x = F.relu(self.fc1(x))
x = F.relu(self.fc2(x))
x = self.fc3(x)
return x

This network consists of three fully connected layers (fc1, fc2, fc3). The first layer has 784 input features (e.g., for MNIST images), the second layer has 128 units, and the third layer has 64 units, which then maps to 10 output classes.

Step 2: Create a Dummy Input

To visualize the network, we need to pass a dummy input through it. This helps in generating a computational graph that can be visualized.

dummy_input = torch.randn(1, 784)  # Batch size of 1, 784 input features

Step 3: Visualize the Network using Torchviz

Now, let's visualize the network using Torchviz. We'll use the make_dot function from Torchviz to generate a graph.

from torchviz import make_dot

model = SimpleNet()
output = model(dummy_input)
dot = make_dot(output, params=dict(model.named_parameters()))

# Save or display the generated graph
dot.format = 'png'
dot.render('simple_net')

The make_dot function generates a visualization of the computational graph, showing the connections between layers and the flow of data. The render method saves the visualization as a PNG image named simple_net.png.

Step 4: View the Generated Visualization

Once the visualization is generated and saved, you can open the image to view the structure of your neural network. The graph will show each layer, the operations applied, and the dimensions of the tensors as they flow through the network.

Complete Code to Visualize Simple Neural Network in PyTorch

Python
import torch import torch.nn as nn import torch.nn.functional as F  class SimpleNet(nn.Module):     def __init__(self):         super(SimpleNet, self).__init__()         self.fc1 = nn.Linear(784, 128)         self.fc2 = nn.Linear(128, 64)         self.fc3 = nn.Linear(64, 10)      def forward(self, x):         x = F.relu(self.fc1(x))         x = F.relu(self.fc2(x))         x = self.fc3(x)         return x dummy_input = torch.randn(1, 784)  # Batch size of 1, 784 input features from torchviz import make_dot  model = SimpleNet() output = model(dummy_input) dot = make_dot(output, params=dict(model.named_parameters()))  # Save or display the generated graph dot.format = 'png' dot.render('simple_net') 

Output:

simple_net

Steps to Visualize a Larger Neural Network in PyTorch

Visualizing a larger neural network in PyTorch involves similar steps to visualizing a smaller one, but you may need to consider the complexity and size of the network when dealing with large models. Here’s how to visualize a larger network using PyTorch, including code and tips for handling more complex architectures.

Step 1: Define a Larger Neural Network

For this example, let's define a larger neural network with several layers.

import torch
import torch.nn as nn
import torch.nn.functional as F

class LargerNet(nn.Module):
def __init__(self):
super(LargerNet, self).__init__()
self.fc1 = nn.Linear(784, 512)
self.fc2 = nn.Linear(512, 256)
self.fc3 = nn.Linear(256, 128)
self.fc4 = nn.Linear(128, 64)
self.fc5 = nn.Linear(64, 10) # Output layer for 10 classes

def forward(self, x):
x = F.relu(self.fc1(x))
x = F.relu(self.fc2(x))
x = F.relu(self.fc3(x))
x = F.relu(self.fc4(x))
x = self.fc5(x)
return x

This network includes five fully connected layers, making it larger and more complex.

Step 2: Create a Dummy Input

Generate a dummy input tensor to visualize the model’s computation graph.

dummy_input = torch.randn(1, 784)  # Batch size of 1, 784 input features

Step 3: Visualize the Network Using Torchviz

Use the torchviz library to create a visual representation of the model. Make sure you have torchviz installed:

from torchviz import make_dot

# Instantiate the model and perform a forward pass
model = LargerNet()
output = model(dummy_input)

# Create a visualization of the computational graph
dot = make_dot(output, params=dict(model.named_parameters()))

# Save or display the generated graph
dot.format = 'png'
dot.render('larger_net')

Step 4: View the Generated Visualization

Open the generated image (larger_net.png) to view the structure of your larger neural network. For large networks, the visualization might be quite complex and detailed.

Complete Code to Visualize Large Neural Network in PyTorch

Python
import torch import torch.nn as nn import torch.nn.functional as F from torchviz import make_dot import numpy as np  # Define a larger neural network class LargerNet(nn.Module):     def __init__(self):         super(LargerNet, self).__init__()         self.fc1 = nn.Linear(784, 512)         self.fc2 = nn.Linear(512, 256)         self.fc3 = nn.Linear(256, 128)         self.fc4 = nn.Linear(128, 64)         self.fc5 = nn.Linear(64, 10)  # Output layer for 10 classes      def forward(self, x):         x = F.relu(self.fc1(x))         x = F.relu(self.fc2(x))         x = F.relu(self.fc3(x))         x = F.relu(self.fc4(x))         x = self.fc5(x)         return x  # Create dummy input dummy_input = torch.randn(1, 784)  # Instantiate the model and perform a forward pass model = LargerNet() output = model(dummy_input)  # Create and save the visualization of the computational graph dot = make_dot(output, params=dict(model.named_parameters())) dot.format = 'png' dot.render('larger_net')  print("Visualization saved as 'larger_net.png'.") 

Output:

larger_net

Visualizing a Pre-trained Model in PyTorch: ResNet

ResNet (Residual Networks) is a deep convolutional network architecture that uses residual blocks to make very deep networks trainable. The residual connections help in training deep networks by mitigating the vanishing gradient problem.

Step 1: Define and Load a ResNet Model

You can use a pre-defined ResNet model from the torchvision library. For this example, we'll use ResNet18, which is a variant of ResNet with 18 layers.

import torch
import torchvision.models as models
from torchviz import make_dot

# Load a pre-trained ResNet18 model
model = models.resnet18(pretrained=True)

# Create a dummy input tensor with the shape expected by ResNet
dummy_input = torch.randn(1, 3, 224, 224) # Batch size of 1, 3 channels, 224x224 image

# Perform a forward pass
output = model(dummy_input)

Step 2: Visualize the Model Using Torchviz

To visualize the ResNet model, you need to generate the computation graph using torchviz and save it.

# Create a visualization of the computational graph
dot = make_dot(output, params=dict(model.named_parameters()))

# Save the generated graph as a PNG file
dot.format = 'png'
dot.render('resnet18')

Step 3: View the Generated Visualization

Open the generated image (resnet18.png) to view the structure of the ResNet model. The graph will show the residual blocks, convolutional layers, and other components.

Complete Code Example

Here's the complete code for defining, visualizing, and saving a ResNet model:

Python
import torch import torchvision.models as models from torchviz import make_dot  # Load a pre-trained ResNet18 model model = models.resnet18(pretrained=True)  # Create a dummy input tensor with the shape expected by ResNet dummy_input = torch.randn(1, 3, 224, 224)  # Batch size of 1, 3 channels, 224x224 image  # Perform a forward pass output = model(dummy_input)  # Create and save the visualization of the computational graph dot = make_dot(output, params=dict(model.named_parameters())) dot.format = 'png' dot.render('resnet18')  print("Visualization saved as 'resnet18.png'.") 

Output:

9a4f27a3-d683-4ab5-8aef-0026dfee2de9

Tips for Visualizing Complex Networks

  1. Network Complexity: For very deep networks like ResNet, the visualization can become cluttered. Consider focusing on specific layers or blocks if the full graph is overwhelming.
  2. Interactive Visualization: For interactive exploration, consider using tools like TensorBoard or Netron, which allow you to explore the model's architecture more interactively.
  3. Model Summary: To complement the graphical visualization, you can use the summary function from torchsummary to get a textual overview of the model:
    from torchsummary import summary
    summary(model, (3, 224, 224))
  4. Export and Explore: If the graph is too complex, you might want to export it in an interactive format or break down the network into smaller parts to visualize them separately.

By following these steps, you can visualize complex models like ResNet in PyTorch and gain valuable insights into their architecture and structure.


Next Article
Graph Neural Networks with PyTorch

M

maheshkadambala
Improve
Article Tags :
  • Deep Learning
  • AI-ML-DS
  • Python-PyTorch
  • AI-ML-DS With Python

Similar Reads

  • Visualizing PyTorch Neural Networks
    Visualizing neural network models is a crucial step in understanding their architecture, debugging, and conveying their design. PyTorch, a popular deep learning framework, offers several tools and libraries that facilitate model visualization. This article will guide you through the process of visua
    4 min read
  • How to Visualize a Neural Network in Python using Graphviz ?
    In this article, We are going to see how to plot (visualize) a neural network in python using Graphviz. Graphviz is a python module that open-source graph visualization software. It is widely popular among researchers to do visualizations. It's representing structural information as diagrams of abst
    4 min read
  • Graph Neural Networks with PyTorch
    Graph Neural Networks (GNNs) represent a powerful class of machine learning models tailored for interpreting data described by graphs. This is particularly useful because many real-world structures are networks composed of interconnected elements, such as social networks, molecular structures, and c
    4 min read
  • How to implement neural networks in PyTorch?
    This tutorial shows how to use PyTorch to create a basic neural network for classifying handwritten digits from the MNIST dataset. Neural networks, which are central to modern AI, enable machines to learn tasks like regression, classification, and generation. With PyTorch, you'll learn how to design
    5 min read
  • How to visualize training progress in PyTorch?
    Deep learning and understanding the mechanics of learning and progress during training is vital to optimize performance while diagnosing problems such as underfitting or overfitting. The process of visualizing training progress offers valuable insights into the dynamics of learning that allow us to
    9 min read
  • Training Neural Networks using Pytorch Lightning
    Introduction: PyTorch Lightning is a library that provides a high-level interface for PyTorch. Problem with PyTorch is that every time you start a project you have to rewrite those training and testing loop. PyTorch Lightning fixes the problem by not only reducing boilerplate code but also providing
    7 min read
  • How to visualize the intermediate layers of a network in PyTorch?
    Visualizing intermediate layers of a neural network in PyTorch can help understand how the network processes input data at different stages. Visualizing intermediate layers helps us see how data changes as it moves through a neural network. We can understand what features the network learns and how
    6 min read
  • Training Neural Networks with Validation using PyTorch
    Neural Networks are a biologically-inspired programming paradigm that deep learning is built around. Python provides various libraries using which you can create and train neural networks over given data. PyTorch is one such library that provides us with various utilities to build and train neural n
    8 min read
  • How to optimize memory usage in PyTorch?
    Memory optimization is essential when using PyTorch, particularly when training deep learning models on GPUs or other devices with restricted memory. Larger model training, quicker training periods, and lower costs in cloud settings may all be achieved with effective memory management. This article
    4 min read
  • A single neuron neural network in Python
    Neural networks are the core of deep learning, a field that has practical applications in many different areas. Today neural networks are used for image classification, speech recognition, object detection, etc. Now, Let's try to understand the basic unit behind all these states of art techniques.A
    3 min read
geeksforgeeks-footer-logo
Corporate & Communications Address:
A-143, 7th Floor, Sovereign Corporate Tower, Sector- 136, Noida, Uttar Pradesh (201305)
Registered Address:
K 061, Tower K, Gulshan Vivante Apartment, Sector 137, Noida, Gautam Buddh Nagar, Uttar Pradesh, 201305
GFG App on Play Store GFG App on App Store
Advertise with us
  • Company
  • About Us
  • Legal
  • Privacy Policy
  • In Media
  • Contact Us
  • Advertise with us
  • GFG Corporate Solution
  • Placement Training Program
  • Languages
  • Python
  • Java
  • C++
  • PHP
  • GoLang
  • SQL
  • R Language
  • Android Tutorial
  • Tutorials Archive
  • DSA
  • Data Structures
  • Algorithms
  • DSA for Beginners
  • Basic DSA Problems
  • DSA Roadmap
  • Top 100 DSA Interview Problems
  • DSA Roadmap by Sandeep Jain
  • All Cheat Sheets
  • Data Science & ML
  • Data Science With Python
  • Data Science For Beginner
  • Machine Learning
  • ML Maths
  • Data Visualisation
  • Pandas
  • NumPy
  • NLP
  • Deep Learning
  • Web Technologies
  • HTML
  • CSS
  • JavaScript
  • TypeScript
  • ReactJS
  • NextJS
  • Bootstrap
  • Web Design
  • Python Tutorial
  • Python Programming Examples
  • Python Projects
  • Python Tkinter
  • Python Web Scraping
  • OpenCV Tutorial
  • Python Interview Question
  • Django
  • Computer Science
  • Operating Systems
  • Computer Network
  • Database Management System
  • Software Engineering
  • Digital Logic Design
  • Engineering Maths
  • Software Development
  • Software Testing
  • DevOps
  • Git
  • Linux
  • AWS
  • Docker
  • Kubernetes
  • Azure
  • GCP
  • DevOps Roadmap
  • System Design
  • High Level Design
  • Low Level Design
  • UML Diagrams
  • Interview Guide
  • Design Patterns
  • OOAD
  • System Design Bootcamp
  • Interview Questions
  • Inteview Preparation
  • Competitive Programming
  • Top DS or Algo for CP
  • Company-Wise Recruitment Process
  • Company-Wise Preparation
  • Aptitude Preparation
  • Puzzles
  • School Subjects
  • Mathematics
  • Physics
  • Chemistry
  • Biology
  • Social Science
  • English Grammar
  • Commerce
  • World GK
  • GeeksforGeeks Videos
  • DSA
  • Python
  • Java
  • C++
  • Web Development
  • Data Science
  • CS Subjects
@GeeksforGeeks, Sanchhaya Education Private Limited, All rights reserved
We use cookies to ensure you have the best browsing experience on our website. By using our site, you acknowledge that you have read and understood our Cookie Policy & Privacy Policy
Lightbox
Improvement
Suggest Changes
Help us improve. Share your suggestions to enhance the article. Contribute your expertise and make a difference in the GeeksforGeeks portal.
geeksforgeeks-suggest-icon
Create Improvement
Enhance the article with your expertise. Contribute to the GeeksforGeeks community and help create better learning resources for all.
geeksforgeeks-improvement-icon
Suggest Changes
min 4 words, max Words Limit:1000

Thank You!

Your suggestions are valuable to us.

What kind of Experience do you want to share?

Interview Experiences
Admission Experiences
Career Journeys
Work Experiences
Campus Experiences
Competitive Exam Experiences