文章目录
-
- Windows Anaconda环境下的安装指南
- 1. 安装 Graphviz
- 2. 安装 PyTorchviz
- 使用示例
-
工具简介:PyTorchviz+Graphviz
- 在深度学习模型开发过程中,理解模型的结构和数据流动对于调试和优化至关重要。PyTorchviz 和 Graphviz 是两个强大的工具,可以帮助我们可视化 PyTorch 模型的计算图。
- PyTorchviz 是一个基于 Graphviz 的 Python 包,专门用于可视化 PyTorch 计算图。它能够:显示模型的前向和后向计算图、展示张量的形状和操作类型、帮助理解复杂的模型架构
- Graphviz 是一个开源的图形可视化软件,它使用 DOT 语言来描述图形,能够自动生成各种复杂的图形布局。PyTorchviz 依赖 Graphviz 来渲染计算图。
Windows Anaconda环境下的安装指南
1. 安装 Graphviz
- 打开https://graphviz.org/download/,选择本平台的安装包。

- 注意安装过程中使用默认路径安装和配置环境变量

- 使用命令验证环境变量配置
dot --version
dot - graphviz version 12.2.1 (20241206.2353)
2. 安装 PyTorchviz
- 在Anaconda Python 环境中安装grahpviz和PyTorchviz:
pip install grahpviz
pip install torchviz
使用示例
基本用法
import torch
from torch import nn
from torchviz import make_dot
import os
os.environ["PATH"] += os.pathsep + 'C:/Program Files/Graphviz/bin'
from torch.onnx import TrainingMode
x = torch.randn(1,8)
model = nn.Sequential(nn.Linear(8, 16),nn.Tanh(),nn.Linear(16, 1)
)
vis_graph = make_dot(model(x), params=dict(model.named_parameters()))
vis_graph.view()
with torch.onnx.select_model_mode_for_export(model, TrainingMode.EVAL):trace= torch.jit.trace(model, (x,))output = trace(x)
print(output)
display(vis_graph)

高级用法
dot = make_dot(y, params=dict(model.named_parameters()),show_attrs=True, show_saved=True)
dot.render('model_graph', format='pdf')
dot = make_dot(y, params=dict(list(model.named_parameters())[:1]))
常见问题解决
- Graphviz 可执行文件未找到
Error: failed to execute ['dot', '-Tpng'], make sure the Graphviz executables are on your systems' PATH
- Jupyter Notebook 中不显示图像:确保安装 ipython,尝试使用
display(dot)
而不是直接输出。