This lab sets up HiddenLayer, a small Python library that draws neural network graphs and plots training metrics, along with the Graphviz bindings it uses to render diagrams. "TensorFlow Hidden Layer" in the title refers to the hiddenlayer package, not to a hidden layer inside a TensorFlow model. Below the notebook you will find a working setup for current Python versions, a test that checks the install, a first PyTorch model diagram, and fixes for the errors you are most likely to hit.
What the notebook above installs and why
The notebook above runs three pip install commands. Each package does a different job, and only two of them matter if you use PyTorch:
| Package | Purpose | Needed for PyTorch visualization? |
|---|---|---|
hiddenlayer | Builds a graph of a model's layers and draws training-progress charts in Jupyter | Yes |
graphviz | Python bindings that pass the graph to the Graphviz dot program for rendering | Yes, and the system Graphviz binaries are also required |
tensorflow | Lets HiddenLayer draw TensorFlow graphs | No, only if you also visualize TensorFlow models |
The captured output shows TensorFlow 1.13.1 on Python 3.7 in an Anaconda environment. Both versions are years past end of life. Current PyTorch and TensorFlow releases do not support Python 3.7, so if you copy that environment exactly, the install will either fail or give you outdated wheels. The notebook also never installs PyTorch itself, even though this is a PyTorch lab.
Prerequisites
- A supported Python 3 release that current PyTorch wheels are built for. Check the PyTorch install selector for the current list.
- Jupyter Notebook or JupyterLab, because HiddenLayer displays graphs inline as SVG.
- The Graphviz system package, which provides the
dotexecutable.pip install graphvizdoes not install it. - A virtual environment or conda environment just for this lab, so these packages don't conflict with other projects.
Corrected setup for current environments
First install the Graphviz binaries with your operating system's package manager. Then create an isolated environment and install the Python packages in it.
# 1. System Graphviz (pick one)
sudo apt-get install -y graphviz # Debian/Ubuntu
brew install graphviz # macOS
# Windows: install Graphviz and add its bin folder to PATH
# 2. Isolated Python environment
python3 -m venv ~/venvs/pytorch-lab
source ~/venvs/pytorch-lab/bin/activate
# 3. Python packages
pip install --upgrade pip
pip install torch graphviz hiddenlayer jupyter
# Optional: only if you also want to draw TensorFlow graphs
# pip install tensorflowCode language: PHP (php)
If you use conda, conda install -c conda-forge graphviz python-graphviz installs both the binaries and the Python bindings into the environment in one step.
If you install from inside a notebook cell, use the %pip magic instead of !pip. %pip always installs into the interpreter that runs the current kernel. !pip runs whichever pip comes first on the shell PATH, which may belong to a different Python.
%pip install torch graphviz hiddenlayer
Note: After you install packages from inside a notebook, restart the kernel before you import them. If you don't, Python may keep using the old modules that are already loaded in memory.
Verify the installation
The notebook above ends with an empty cell and never checks that anything works. Run this cell to confirm that each package imports and that the Python bindings can find the dot executable:
import torch
import graphviz
import hiddenlayer as hl
print("PyTorch:", torch.__version__)
print("Graphviz dot:", graphviz.version()) # calls the dot binary
print("HiddenLayer imported OK")Code language: PHP (php)
graphviz.version() returns a tuple such as (2, 43, 0). If it raises ExecutableNotFound, the Python package is installed but the system Graphviz binaries are missing or not on PATH.
Draw your first PyTorch model graph
HiddenLayer traces the model with a dummy input tensor and builds a graph of the operations. The dummy input must have the shape the model expects, including the batch dimension.
import torch
import torch.nn as nn
import hiddenlayer as hl
model = nn.Sequential(
nn.Linear(784, 128),
nn.ReLU(),
nn.Linear(128, 64),
nn.ReLU(),
nn.Linear(64, 10),
)
# Trace the model with a dummy batch of one flattened 28x28 image
graph = hl.build_graph(model, torch.zeros([1, 784]))
# Write the diagram to disk (model_graph.png)
graph.save("model_graph", format="png")
# As the last expression in a cell, the graph renders inline in Jupyter
graphCode language: PHP (php)
You should see a top-to-bottom diagram of Linear and Relu nodes with tensor shapes on the edges. HiddenLayer merges common layer sequences into single blocks to keep large networks readable.
Common errors and fixes
| Error | Cause | Fix |
|---|---|---|
ExecutableNotFound: failed to execute 'dot' | Only the Python graphviz package is installed | Install the system Graphviz package and make sure dot -V works in a terminal |
ModuleNotFoundError: No module named 'hiddenlayer' right after !pip install | pip installed the package into a different Python than the kernel uses | Use %pip install, then restart the kernel |
AttributeError about a torch.onnx function such as _optimize_trace | HiddenLayer calls private PyTorch internals that newer PyTorch releases removed | Use an older PyTorch in a dedicated environment, or switch to one of the alternatives below |
Shape mismatch inside build_graph | The dummy input shape doesn't match the model's first layer | Pass a tensor with the same shape as one real batch, for example torch.zeros([1, 3, 224, 224]) for an image CNN |
| No TensorFlow wheel available for your Python version | The Python version is too new or too old for current TensorFlow builds | Skip TensorFlow if you only need PyTorch, or use a Python version that TensorFlow supports |
Note: HiddenLayer has not been actively maintained for several years. It works well for learning on older PyTorch versions. For long-lived projects, use one of the maintained tools below.
Maintained alternatives for visualizing PyTorch models
Each of these tools works with current PyTorch and covers the same need as HiddenLayer:
# pip install torchinfo torchviz tensorboard
import torch
from torchinfo import summary
from torchviz import make_dot
from torch.utils.tensorboard import SummaryWriter
x = torch.zeros([1, 784])
# 1. Text summary of layers, output shapes and parameter counts
summary(model, input_size=(1, 784))
# 2. Autograd graph rendered with Graphviz
make_dot(model(x), params=dict(model.named_parameters())).render("autograd_graph", format="png")
# 3. Interactive graph in TensorBoard (view with: tensorboard --logdir runs)
writer = SummaryWriter("runs/lab8")
writer.add_graph(model, x)
writer.close()Code language: PHP (php)
- torchinfo prints a Keras-style summary. Use it to check shapes and parameter counts quickly.
- torchviz draws the backward (autograd) graph. Like HiddenLayer, it needs the system Graphviz binaries.
- TensorBoard needs only the
tensorboardpackage, not TensorFlow. It also tracks loss and accuracy curves, which replaces HiddenLayer'sHistoryandCanvastraining plots. - Netron opens exported ONNX or saved model files in a desktop or browser viewer.
Frequently asked questions
Do I need TensorFlow to use HiddenLayer with PyTorch?
No. TensorFlow is only needed if you want HiddenLayer to draw TensorFlow graphs. For PyTorch models, you need torch, hiddenlayer, graphviz and the system Graphviz binaries.
Why does pip install graphviz still give a 'dot' not found error?
The graphviz pip package contains only Python bindings. It calls the dot program, which comes from the Graphviz system package. Install that with apt, brew, conda or the Windows installer, and make sure its bin folder is on PATH.
What is the difference between !pip and %pip in Jupyter?
!pip runs a shell command, so it may install into a different Python than the one your kernel uses. %pip always targets the kernel's own environment, which is why it is the recommended way to install packages from a notebook.
Does HiddenLayer work with the latest PyTorch?
Often it does not, because it relies on private torch.onnx functions that newer PyTorch releases changed or removed. For current PyTorch, use torchinfo, torchviz or TensorBoard's add_graph instead.
Can TensorBoard show a PyTorch model graph without installing TensorFlow?
Yes. Install the tensorboard package, log the graph with torch.utils.tensorboard.SummaryWriter.add_graph, and run tensorboard --logdir runs.
Related tutorials
- More Machine Learning tutorials
- Staff MLOps Engineer: Role Blueprint, Responsibilities, Skills, KPIs, and Career Path
- Lead Machine Learning Engineer: Role Blueprint, Responsibilities, Skills, KPIs, and Career Path
I’m Rajesh Kumar, a DevOps, SRE, DevSecOps, Cloud, and Platform Engineering expert passionate about sharing practical knowledge, real-world experiences, and industry best practices. I have worked at Cotocus and regularly write about technology, travel, investing, health, product reviews, and digital marketing through my various platforms.
I publish technical articles at DevOps School, travel stories at Holiday Landmark, stock market insights at Stocks Mantra, health and fitness guidance at My Medic Plus, product reviews at TrueReviewNow, and SEO and digital marketing strategies at Wizbrand.
Find Trusted Cardiac Hospitals
Compare heart hospitals by city and services โ all in one place.
Explore Hospitals