PyTorch 学习笔记(二): 可视化与模型参数计算

PyTorch 学习笔记(二):可视化与模型参数计算

1. 可视化

from models import Darknet
from torchviz import make_dot, make_dot_from_trace
import torch
from tensorboardX import SummaryWriter

# torchviz 可视化
model = torch.nn.Sequential()
model.add_module('W0', torch.nn.Linear(8, 16))
model.add_module('tanh', torch.nn.Tanh())
model.add_module('W1', torch.nn.Linear(16, 1))
x = torch.randn(1,8)
g = make_dot(model(x), params=dict(model.named_parameters()))
g.view()

# hiddenlayer 可视化
# pip install hiddenlayer
import torchvision
# Resnet101
model = torchvision.models.resnet101()

# Rather than using the default transforms, build custom ones to group
# nodes of residual and bottleneck blocks.
transforms = [
    # Fold Conv, BN, RELU layers into one
    # Fold Conv, BN layers together
    hl.transforms.Fold("Conv > BatchNorm", "ConvBn"),
    # Fold bottleneck blocks
    hl.transforms.Fold("""
           ((ConvBnRelu > ConvBnRelu > ConvBn) | ConvBn) > Add > Relu
           """, "BottleneckBlock", "Bottleneck Block"),
    # Fold residual blocks
    hl.transforms.Fold("""ConvBnRelu > ConvBnRelu > ConvBn > Add > Relu""",
                       "ResBlock", "Residual Block"),
    # Fold repeated blocks
    hl.transforms.FoldDuplicates(), ]

# Display graph using the transforms above
g = hl.build_graph(model, torch.zeros([1, 3, 224, 224]), transforms=transforms)
g.save('1.pdf')

# tensorboardx 可视化
 writer = SummaryWriter(logdir="./logs/", comment="TestView")
 with writer:
     writer.add_graph(model, input_to_model=torch.rand(1, 8))
# 命令行窗口输入 tensorboard --logdir logs
# 浏览器输入以下网址
# http://localhost:6006

torchviz

hl
tensorboardx

2. 计算模型参数

# 计算模型参数个数
def get_parameter_number(net):
    total_num = sum(p.numel() for p in net.parameters())
    trainable_num = sum(p.numel() for p in net.parameters() if p.requires_grad)
    return {'Total': total_num, 'Trainable': trainable_num}
print(get_parameter_number(model))
# 结果: {'Trainable': 161, 'Total': 161}

参考文献
1.可视化参考
2.计算参数参考
3.深度特征可视化

  • 0
    点赞
  • 3
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值