pytorch查看模型weight与grad方式


Posted in Python onJune 24, 2020

在用pdb debug的时候,有时候需要看一下特定layer的权重以及相应的梯度信息,如何查看呢?

1. 首先把你的模型打印出来,像这样

pytorch查看模型weight与grad方式

2. 然后观察到model下面有module的key,module下面有features的key, features下面有(0)的key,这样就可以直接打印出weight了,在pdb debug界面输入p model.module.features[0].weight,就可以看到weight,输入 p model.module.features[0].weight.grad就可以查看梯度信息

pytorch查看模型weight与grad方式

pytorch查看模型weight与grad方式

补充知识:查看Pytorch网络的各层输出(feature map)、权重(weight)、偏置(bias)

BatchNorm2d参数量

torch.nn.BatchNorm2d(num_features, eps=1e-05, momentum=0.1, affine=True, track_running_stats=True)
# 卷积层中卷积核的数量C 
num_features ? C from an expected input of size (N, C, H, W)
>>> import torch
>>> m = torch.nn.BatchNorm2d(100)
>>> m.weight.shape
torch.Size([100])
>>> m.numel()
AttributeError: 'BatchNorm2d' object has no attribute 'numel'
>>> m.weight.numel()
100
>>> m.parameters().numel()
Traceback (most recent call last):
 File "<stdin>", line 1, in <module>
AttributeError: 'generator' object has no attribute 'numel'
>>> [p.numel() for p in m.parameters()]
[100, 100]

linear层

>>> import torch
>>> m1 = torch.nn.Linear(100,10)
# 参数数量= (输入神经元+1)*输出神经元
>>> m1.weight.shape
torch.Size([10, 100])
>>> m1.bias.shape
torch.Size([10])
>>> m1.bias.numel()
10
>>> m1.weight.numel()
1000
>>> m11 = list(m1.parameters())
>>> m11[0].shape
# weight
torch.Size([10, 100])
>>> m11[1].shape
# bias
torch.Size([10])

weight and bias

# Method 1 查看Parameters的方式多样化,直接访问即可
model = alexnet(pretrained=True).to(device)
conv1_weight = model.features[0].weight# Method 2 
# 这种方式还适合你想自己参考一个预训练模型写一个网络,各层的参数不变,但网络结构上表述有所不同
# 这样你就可以把param迭代出来,赋给你的网络对应层,避免直接load不能匹配的问题!
for layer,param in model.state_dict().items(): # param is weight or bias(Tensor) 
 print layer,param

feature map

由于pytorch是动态网络,不存储计算数据,查看各层输出的特征图并不是很方便!分下面两种情况讨论:

1、你想查看的层是独立的,那么你在forward时用变量接收并返回即可!!

class Net(nn.Module):
  def __init__(self):
    self.conv1 = nn.Conv2d(1, 1, 3)
    self.conv2 = nn.Conv2d(1, 1, 3)
    self.conv3 = nn.Conv2d(1, 1, 3)  def forward(self, x):
    out1 = F.relu(self.conv1(x))
    out2 = F.relu(self.conv2(out1))
    out3 = F.relu(self.conv3(out2))
    return out1, out2, out3

2、你的想看的层在nn.Sequential()顺序容器中,这个麻烦些,主要有以下几种思路:

# Method 1 巧用nn.Module.children()
# 在模型实例化之后,利用nn.Module.children()删除你查看的那层的后面层
import torch
import torch.nn as nn
from torchvision import modelsmodel = models.alexnet(pretrained=True)# remove last fully-connected layer
new_classifier = nn.Sequential(*list(model.classifier.children())[:-1])
model.classifier = new_classifier
# Third convolutional layer
new_features = nn.Sequential(*list(model.features.children())[:5])
model.features = new_features
# Method 2 巧用hook,推荐使用这种方式,不用改变原有模型
# torch.nn.Module.register_forward_hook(hook)
# hook(module, input, output) -> Nonemodel = models.alexnet(pretrained=True)
# 定义
def hook (module,input,output):
  print output.size()
# 注册
handle = model.features[0].register_forward_hook(hook)
# 删除句柄
handle.remove()# torch.nn.Module.register_backward_hook(hook)
# hook(module, grad_input, grad_output) -> Tensor or None
model = alexnet(pretrained=True).to(device)
outputs = []
def hook (module,input,output):
  outputs.append(output)
  print len(outputs)handle = model.features[0].register_backward_hook(hook)

注:还可以通过定义一个提取特征的类,甚至是重构成各层独立相同模型将问题转化成第一种

计算模型参数数量

def count_parameters(model):
return sum(p.numel() for p in model.parameters() if p.requires_grad)

以上这篇pytorch查看模型weight与grad方式就是小编分享给大家的全部内容了,希望能给大家一个参考,也希望大家多多支持三水点靠木。

Python 相关文章推荐
python解决方案:WindowsError: [Error 2]
Aug 28 Python
总结python实现父类调用两种方法的不同
Jan 15 Python
python爬虫入门教程--HTML文本的解析库BeautifulSoup(四)
May 25 Python
Python探索之创建二叉树
Oct 25 Python
Python爬虫设置代理IP的方法(爬虫技巧)
Mar 04 Python
Flask框架使用DBUtils模块连接数据库操作示例
Jul 20 Python
使用python验证代理ip是否可用的实现方法
Jul 25 Python
Python Lambda函数使用总结详解
Dec 11 Python
Python MySQL 日期时间格式化作为参数的操作
Mar 02 Python
Python Tornado之跨域请求与Options请求方式
Mar 28 Python
python interpolate插值实例
Jul 06 Python
详解NumPy中的线性关系与数据修剪压缩
May 25 Python
pytorch  网络参数 weight bias 初始化详解
Jun 24 #Python
可视化pytorch 模型中不同BN层的running mean曲线实例
Jun 24 #Python
python3.x中安装web.py步骤方法
Jun 23 #Python
python如何删除文件、目录
Jun 23 #Python
TensorFlow保存TensorBoard图像操作
Jun 23 #Python
python和js交互调用的方法
Jun 23 #Python
virtualenv介绍及简明教程
Jun 23 #Python
You might like
给初学者的30条PHP最佳实践(荒野无灯)
2011/08/02 PHP
ThinkPHP的I方法使用详解
2014/06/18 PHP
PHP中使用SimpleXML检查XML文件结构实例
2015/01/07 PHP
网站被恶意镜像怎么办 php一段代码轻松搞定(全面版)
2018/10/23 PHP
JavaScript 实现类的多种方法实例
2013/05/01 Javascript
jq实现酷炫的鼠标经过图片翻滚效果
2014/03/12 Javascript
JSON.stringify转换JSON时日期时间不准确的解决方法
2014/08/08 Javascript
JS数组的常见用法实例
2015/02/10 Javascript
jQuery源码解读之removeAttr()方法分析
2015/02/20 Javascript
jquery实现点击向下展开菜单项(伸缩导航)效果
2015/08/22 Javascript
jQuery数据检索中根据关键字快速定位GridView指定行的实现方法
2016/06/08 Javascript
Bootstrap table的使用方法
2016/11/02 Javascript
原生JS获取元素集合的子元素宽度实例
2016/12/14 Javascript
基于Vue单文件组件详解
2017/09/15 Javascript
vue实现树形菜单效果
2018/03/19 Javascript
微信小程序实现分享商品海报功能
2019/09/30 Javascript
js实现带箭头的进度流程
2020/03/26 Javascript
[05:02]2014DOTA2 TI中国区预选赛精彩TOPPLAY第三弹
2014/06/25 DOTA
Python+tkinter使用80行代码实现一个计算器实例
2018/01/16 Python
Pycharm 设置自定义背景颜色的图文教程
2018/05/23 Python
python将字符串list写入excel和txt的实例
2019/07/20 Python
python中利用numpy.array()实现俩个数值列表的对应相加方法
2019/08/26 Python
在python tkinter界面中添加按钮的实例
2020/03/04 Python
MyFrenchPharma中文网:最大的法国药妆平台
2016/10/07 全球购物
办公室文秘自我鉴定
2013/09/21 职场文书
汽车驾驶求职信
2013/10/25 职场文书
党校学习思想汇报
2014/01/06 职场文书
写演讲稿要注意的六件事
2014/01/14 职场文书
大学毕业自我评价
2014/02/02 职场文书
倡议书格式
2014/08/30 职场文书
购房公证委托书(2014版)
2014/09/12 职场文书
2015年安全教育月活动总结
2015/03/26 职场文书
小学秋季运动会通讯稿
2015/11/25 职场文书
写作技巧:如何撰写一份优秀的营销策划书
2019/08/13 职场文书
Go遍历struct,map,slice的实现
2021/06/13 Golang
Mysql 数据库中的 redo log 和 binlog 写入策略
2022/04/26 MySQL