目录
1--利用netron库可视化神经网络
2--利用tensorboard可视化神经网络
3--参考
1--利用netron库可视化神经网络
介绍:netron是一个深度学习模型可视化库,其可视化pytorch神经网络模型的两个步骤为:
①pytorch保存神经网络模型为onnx格式,代码如下:
torch.onnx.export(model, data, onnx_path)
# model为神经网络模型
# data为模型输入数据
# onnx_path为模型保存的文件名
②导入onnx模型文件至netron,实现可视化,代码如下:
netron.start(onnx_path)
# onnx_path为onnx格式神经网络的文件名
完整示例代码如下:
# 导入第三方库
import torch
import torch.nn as nn
import torch.nn.functional as F
import torch.onnx
import netron
# 搭建神经网络模型
class model(nn.Module):
def __init__(self):
super(model, self).__init__()
self.conv1 = nn.Conv2d(3, 64, 3, padding=1, bias=False)
self.block1 = nn.Sequential(
nn.Conv2d(64, 64, 3, padding=1, bias=False),
nn.BatchNorm2d(64),
nn.ReLU(inplace=True),
nn.Conv2d(64, 32, 1, bias=False),
nn.BatchNorm2d(32),
nn.ReLU(inplace=True),
nn.Conv2d(32, 64, 3, padding=1, bias=False),
nn.BatchNorm2d(64)
)
self.output = nn.Sequential(
nn.Conv2d(64, 1, 3, padding=1, bias=True),
nn.Sigmoid()
)
def forward(self, x):
x = self.conv1(x)
residual = x
x = F.relu(self.block1(x) + residual)
x = self.output(x)
return x
model = model() # 模型
data = torch.rand(1, 3, 416, 416) # 数据
onnx_path = "onnx_model_name.onnx" # 文件名
torch.onnx.export(model, data, onnx_path) # 导出神经网络模型为onnx格式
netron.start(onnx_path) # 启动netron
可视化效果:
2--利用tensorboard可视化神经网络
???????代码:
# 导入第三方库
import torch
import torch.nn as nn
import torch.nn.functional as F
from tensorboardX import SummaryWriter
from torch.autograd import Variable
# 搭建神经网络模型
class Net(nn.Module):
def __init__(self):
super(Net, self).__init__()
self.conv1 = nn.Conv2d(3, 64, 3, padding=1, bias=False)
self.block1 = nn.Sequential(
nn.Conv2d(64, 64, 3, padding=1, bias=False),
nn.BatchNorm2d(64),
nn.ReLU(inplace=True),
nn.Conv2d(64, 32, 1, bias=False),
nn.BatchNorm2d(32),
nn.ReLU(inplace=True),
nn.Conv2d(32, 64, 3, padding=1, bias=False),
nn.BatchNorm2d(64)
)
self.output = nn.Sequential(
nn.Conv2d(64, 1, 3, padding=1, bias=True),
nn.Sigmoid()
)
def forward(self, x):
x = self.conv1(x)
residual = x
x = F.relu(self.block1(x) + residual)
x = self.output(x)
return x
Input_data = Variable(torch.rand(1, 3, 416, 416)) # 输入数据
Model = Net() # 模型
with SummaryWriter(comment = 'Net') as w:
w.add_graph(Model, (Input_data, ))
运行代码后会生成一个runs的文件夹,里面拥有一个events.out.tfevents的文件,执行以下代码:
tensorboard --logdir path
# path为events.out.tfevents文件所在文件夹的路径
结果:打开下图红框的网址即可查看和下载可视化的神经网络模型
3--参考
参考链接1???????
|