How to Visualize PyTorch Neural Networks
Last Updated :
23 Jul, 2025
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.
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.
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:
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.
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:
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:
Tips for Visualizing Complex Networks
- 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.
- Interactive Visualization: For interactive exploration, consider using tools like TensorBoard or Netron, which allow you to explore the model's architecture more interactively.
- 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))
- 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.
Similar Reads
Deep Learning Tutorial Deep Learning is a subset of Artificial Intelligence (AI) that helps machines to learn from large datasets using multi-layered neural networks. It automatically finds patterns and makes predictions and eliminates the need for manual feature extraction. Deep Learning tutorial covers the basics to adv
5 min read
Deep Learning Basics
Introduction to Deep LearningDeep Learning is transforming the way machines understand, learn and interact with complex data. Deep learning mimics neural networks of the human brain, it enables computers to autonomously uncover patterns and make informed decisions from vast amounts of unstructured data. How Deep Learning Works?
7 min read
Artificial intelligence vs Machine Learning vs Deep LearningNowadays many misconceptions are there related to the words machine learning, deep learning, and artificial intelligence (AI), most people think all these things are the same whenever they hear the word AI, they directly relate that word to machine learning or vice versa, well yes, these things are
4 min read
Deep Learning Examples: Practical Applications in Real LifeDeep learning is a branch of artificial intelligence (AI) that uses algorithms inspired by how the human brain works. It helps computers learn from large amounts of data and make smart decisions. Deep learning is behind many technologies we use every day like voice assistants and medical tools.This
3 min read
Challenges in Deep LearningDeep learning, a branch of artificial intelligence, uses neural networks to analyze and learn from large datasets. It powers advancements in image recognition, natural language processing, and autonomous systems. Despite its impressive capabilities, deep learning is not without its challenges. It in
7 min read
Why Deep Learning is ImportantDeep learning has emerged as one of the most transformative technologies of our time, revolutionizing numerous fields from computer vision to natural language processing. Its significance extends far beyond just improving predictive accuracy; it has reshaped entire industries and opened up new possi
5 min read
Neural Networks Basics
What is a Neural Network?Neural networks are machine learning models that mimic the complex functions of the human brain. These models consist of interconnected nodes or neurons that process data, learn patterns and enable tasks such as pattern recognition and decision-making.In this article, we will explore the fundamental
12 min read
Types of Neural NetworksNeural networks are computational models that mimic the way biological neural networks in the human brain process information. They consist of layers of neurons that transform the input data into meaningful outputs through a series of mathematical operations. In this article, we are going to explore
7 min read
Layers in Artificial Neural Networks (ANN)In Artificial Neural Networks (ANNs), data flows from the input layer to the output layer through one or more hidden layers. Each layer consists of neurons that receive input, process it, and pass the output to the next layer. The layers work together to extract features, transform data, and make pr
4 min read
Activation functions in Neural NetworksWhile building a neural network, one key decision is selecting the Activation Function for both the hidden layer and the output layer. It is a mathematical function applied to the output of a neuron. It introduces non-linearity into the model, allowing the network to learn and represent complex patt
8 min read
Feedforward Neural NetworkFeedforward Neural Network (FNN) is a type of artificial neural network in which information flows in a single direction i.e from the input layer through hidden layers to the output layer without loops or feedback. It is mainly used for pattern recognition tasks like image and speech classification.
6 min read
Backpropagation in Neural NetworkBack Propagation is also known as "Backward Propagation of Errors" is a method used to train neural network . Its goal is to reduce the difference between the modelâs predicted output and the actual output by adjusting the weights and biases in the network.It works iteratively to adjust weights and
9 min read
Deep Learning Models
Deep Learning Frameworks
TensorFlow TutorialTensorFlow is an open-source machine-learning framework developed by Google. It is written in Python, making it accessible and easy to understand. It is designed to build and train machine learning (ML) and deep learning models. It is highly scalable for both research and production.It supports CPUs
2 min read
Keras TutorialKeras high-level neural networks APIs that provide easy and efficient design and training of deep learning models. It is built on top of powerful frameworks like TensorFlow, making it both highly flexible and accessible. Keras has a simple and user-friendly interface, making it ideal for both beginn
3 min read
PyTorch TutorialPyTorch is an open-source deep learning framework designed to simplify the process of building neural networks and machine learning models. With its dynamic computation graph, PyTorch allows developers to modify the networkâs behavior in real-time, making it an excellent choice for both beginners an
7 min read
Caffe : Deep Learning FrameworkCaffe (Convolutional Architecture for Fast Feature Embedding) is an open-source deep learning framework developed by the Berkeley Vision and Learning Center (BVLC) to assist developers in creating, training, testing, and deploying deep neural networks. It provides a valuable medium for enhancing com
8 min read
Apache MXNet: The Scalable and Flexible Deep Learning FrameworkIn the ever-evolving landscape of artificial intelligence and deep learning, selecting the right framework for building and deploying models is crucial for performance, scalability, and ease of development. Apache MXNet, an open-source deep learning framework, stands out by offering flexibility, sca
6 min read
Theano in PythonTheano is a Python library that allows us to evaluate mathematical operations including multi-dimensional arrays efficiently. It is mostly used in building Deep Learning Projects. Theano works way faster on the Graphics Processing Unit (GPU) rather than on the CPU. This article will help you to unde
4 min read
Model Evaluation
Deep Learning Projects