上班时间摸鱼写个博客。
搞了4.5个小时的Pytorch模型可视化:
一.netron
1.命令行端口模式
d = torch.rand(1, 3, 416, 416)
m = model()
o = m(d)
onnx_path = "onnx_model_name.onnx"
torch.onnx.export(m, d, onnx_path)
netron.start(onnx_path)
2.软件客户端模式
import torch.nn as nn
import torch.nn.functional as F
import torch
device = torch.device('cuda' if torch.cuda.is_available() else 'cpu')
class Net(nn.Module):
def __init__(self):
super(Net, self).__init__()
self.conv1 = nn.Conv2d(in_channels=1, out_channels=10, kernel_size=5)
self.conv2 = nn.Conv2d(10, 20, 5)
self.conv3 = nn.Conv2d(20, 40, 3)
self.mp = nn.MaxPool2d(2)
self.mp1 = nn.MaxPool2d(2)
self.fc1 = nn.Linear(2560, 512)
self.fc2 = nn.Linear(512, 10)
def forward(self, x):
in_size = x.size(0)
x = F.relu(self.mp(self.conv1(x)))
x = F.relu(self.mp(self.conv2(x)))
x = F.relu(self.mp1(self.conv3(x)))
x = x.view(in_size, -1)
x = self.fc1(x)
x = self.fc2(x)
return F.log_softmax(x, dim=1)
model = Net().to(device)
torch.save(model, './model_para.pth')
#torch.save(model.state_dict(), './model_para.pth')保存网络时要保存完整结构,不能只保存参数(如代码中的最后一行注释)
没尝试,因为集群不支持远程打开端口,另外模型文件类型是.pth.tar,加载时默认网络参数是被覆盖可更改的,不能被打开。
不过这个应该是最方便的,这个现在可以利用软件直接打开.pth文件,甚至还可以更方便,将pth后缀的文件的默认打开方式改为Netron,直接双击打开。
二.tensorboardX
from torch.autograd import Variable
from tensorboardX import SummaryWriter
# 模拟输入数据
input_data = Variable(torch.rand(16, 3, 224, 224))
# 从torchvision中导入已有模型
net = torchvision.models.resnet18()
# 声明writer对象,保存的文件夹,异己名称
writer = SummaryWriter(log_dir='./log', comment='resnet18')
with writer:
报错太多次:
1.模型有并行,报错模型有变量
2.版本原因导致torch.jit无法运行
3.返回是dict报错
4.assert报错
三.netscope
caffee,.protext, 不支持pytorch,要废了
四、最终方案
看forward函数+理解模型,不可视化了
网友评论