模型参数计算
https://www.cnblogs.com/xuanyuyt/p/12653041.html#_label4
flops-counter.pytorch
地址:https://github.com/sovrasov/flops-counter.pytorch
import torch
from ptflops import get_model_complexity_info
from models import nin
shape = (3, 32, 32)
# 加载训练完毕的模型
with torch.cuda.device(0):
model = nin.Net()
model.load_state_dict(torch.load("./models_save/nin.pth")["state_dict"])
flops, params = get_model_complexity_info(model, shape, as_strings=True, print_per_layer_stat=True)
print('{:<30} {:<8}'.format('Computational complexity: ', flops))
print('{:<30} {:<8}'.format('Number of parameters: ', params))
乘积累加运算(英语:Multiply Accumulate, MAC)
参考:https://www.zhihu.com/question/65305385
thop
https://pypi.org/project/thop/
pip install --upgrade git+https://github.com/Lyken17/pytorch-OpCounter.git
from torchvision.models import resnet50
from thop import profile
model = resnet50()
input = torch.randn(1, 3, 224, 224)
macs, params = profile(model, inputs=(input, ))
"""
# 加载训练的模型
import torch
from torchvision.models import resnet50
from thop import profile
from models import nin
model = nin.Net()
model.load_state_dict(torch.load("./models_save/nin.pth")["state_dict"])
input = torch.randn(1, 3, 32, 32)
macs, params = profile(model, inputs=(input, ))
print("macs", macs)
print("params", params)
"""
模型可视化
netron
https://github.com/lutzroeder/netron
PlotNeuralNet
https://github.com/HarisIqbal88/PlotNeuralNet
hiddenlayer
https://github.com/waleedka/hiddenlayer
NN-SVG
http://alexlenail.me/NN-SVG/LeNet.html
代码生成
from graphviz import Digraph
import torch
from torch.autograd import Variable
import torchvision
def make_dot(var, params=None):
""" Produces Graphviz representation of PyTorch autograd graph
Blue nodes are the Variables that require grad, orange are Tensors
saved for backward in torch.autograd.Function
Args:
var: output Variable
params: dict of (name, Variable) to add names to node that
require grad (TODO: make optional)
"""
if params is not None:
assert isinstance(params.values()[0], Variable)
param_map = {id(v): k for k, v in params.items()}
node_attr = dict(style='filled',
shape='box',
align='left',
fontsize='12',
ranksep='0.1',
height='0.2')
dot = Digraph(node_attr=node_attr, graph_attr=dict(size="12,12"))
seen = set()
def size_to_str(size):
return '('+(', ').join(['%d' % v for v in size])+')'
def add_nodes(var):
if var not in seen:
if torch.is_tensor(var):
dot.node(str(id(var)), size_to_str(var.size()), fillcolor='orange')
elif hasattr(var, 'variable'):
u = var.variable
name = param_map[id(u)] if params is not None else ''
node_name = '%s\n %s' % (name, size_to_str(u.size()))
dot.node(str(id(var)), node_name, fillcolor='lightblue')
else:
dot.node(str(id(var)), str(type(var).__name__))
seen.add(var)
if hasattr(var, 'next_functions'):
for u in var.next_functions:
if u[0] is not None:
dot.edge(str(id(u[0])), str(id(var)))
add_nodes(u[0])
if hasattr(var, 'saved_tensors'):
for t in var.saved_tensors:
dot.edge(str(id(t)), str(id(var)))
add_nodes(t)
add_nodes(var.grad_fn)
return dot
model = torchvision.models.resnet18()
data = torch.rand(1, 3, 128, 128)
y = model(data)
g = make_dot(y)
g.view() # 会生成一个 pdf 文件
draw.io
参考:https://mp.weixin.qq.com/s/MMzvZA55Xb2sOA7rJiXiEw
训练可视化
pytorch-cnn-visualizations
https://github.com/utkuozbulak/pytorch-cnn-visualizations