模型参数计算

https://www.cnblogs.com/xuanyuyt/p/12653041.html#_label4

flops-counter.pytorch

地址:https://github.com/sovrasov/flops-counter.pytorch

  1. import torch
  2. from ptflops import get_model_complexity_info
  3. from models import nin
  4. shape = (3, 32, 32)
  5. # 加载训练完毕的模型
  6. with torch.cuda.device(0):
  7. model = nin.Net()
  8. model.load_state_dict(torch.load("./models_save/nin.pth")["state_dict"])
  9. flops, params = get_model_complexity_info(model, shape, as_strings=True, print_per_layer_stat=True)
  10. print('{:<30} {:<8}'.format('Computational complexity: ', flops))
  11. print('{:<30} {:<8}'.format('Number of parameters: ', params))

image.png

乘积累加运算(英语:Multiply Accumulate, MAC)
参考:https://www.zhihu.com/question/65305385

thop

https://pypi.org/project/thop/

  1. pip install --upgrade git+https://github.com/Lyken17/pytorch-OpCounter.git
  1. from torchvision.models import resnet50
  2. from thop import profile
  3. model = resnet50()
  4. input = torch.randn(1, 3, 224, 224)
  5. macs, params = profile(model, inputs=(input, ))
  6. """
  7. # 加载训练的模型
  8. import torch
  9. from torchvision.models import resnet50
  10. from thop import profile
  11. from models import nin
  12. model = nin.Net()
  13. model.load_state_dict(torch.load("./models_save/nin.pth")["state_dict"])
  14. input = torch.randn(1, 3, 32, 32)
  15. macs, params = profile(model, inputs=(input, ))
  16. print("macs", macs)
  17. print("params", params)
  18. """

模型可视化

netron

https://github.com/lutzroeder/netronscreenshot.png

PlotNeuralNet

https://github.com/HarisIqbal88/PlotNeuralNet

50308846-c2231880-049c-11e9-8763-3daa1024de78.png

hiddenlayer

https://github.com/waleedka/hiddenlayer

NN-SVG

http://alexlenail.me/NN-SVG/LeNet.html

image.png

代码生成

  1. from graphviz import Digraph
  2. import torch
  3. from torch.autograd import Variable
  4. import torchvision
  5. def make_dot(var, params=None):
  6. """ Produces Graphviz representation of PyTorch autograd graph
  7. Blue nodes are the Variables that require grad, orange are Tensors
  8. saved for backward in torch.autograd.Function
  9. Args:
  10. var: output Variable
  11. params: dict of (name, Variable) to add names to node that
  12. require grad (TODO: make optional)
  13. """
  14. if params is not None:
  15. assert isinstance(params.values()[0], Variable)
  16. param_map = {id(v): k for k, v in params.items()}
  17. node_attr = dict(style='filled',
  18. shape='box',
  19. align='left',
  20. fontsize='12',
  21. ranksep='0.1',
  22. height='0.2')
  23. dot = Digraph(node_attr=node_attr, graph_attr=dict(size="12,12"))
  24. seen = set()
  25. def size_to_str(size):
  26. return '('+(', ').join(['%d' % v for v in size])+')'
  27. def add_nodes(var):
  28. if var not in seen:
  29. if torch.is_tensor(var):
  30. dot.node(str(id(var)), size_to_str(var.size()), fillcolor='orange')
  31. elif hasattr(var, 'variable'):
  32. u = var.variable
  33. name = param_map[id(u)] if params is not None else ''
  34. node_name = '%s\n %s' % (name, size_to_str(u.size()))
  35. dot.node(str(id(var)), node_name, fillcolor='lightblue')
  36. else:
  37. dot.node(str(id(var)), str(type(var).__name__))
  38. seen.add(var)
  39. if hasattr(var, 'next_functions'):
  40. for u in var.next_functions:
  41. if u[0] is not None:
  42. dot.edge(str(id(u[0])), str(id(var)))
  43. add_nodes(u[0])
  44. if hasattr(var, 'saved_tensors'):
  45. for t in var.saved_tensors:
  46. dot.edge(str(id(t)), str(id(var)))
  47. add_nodes(t)
  48. add_nodes(var.grad_fn)
  49. return dot
  50. model = torchvision.models.resnet18()
  51. data = torch.rand(1, 3, 128, 128)
  52. y = model(data)
  53. g = make_dot(y)
  54. g.view() # 会生成一个 pdf 文件

draw.io

https://www.draw.io/

image.png

参考:https://mp.weixin.qq.com/s/MMzvZA55Xb2sOA7rJiXiEw

训练可视化

pytorch-cnn-visualizations


https://github.com/utkuozbulak/pytorch-cnn-visualizations

image.png