pytorch获取模型某一层参数名及参数值方式

作者:HuiYu-Li 时间:2022-07-03 06:10:28 

1、Motivation:

I wanna modify the value of some param;

I wanna check the value of some param.

The needed function:

2、state_dict() #generator type

model.modules()#generator type

named_parameters()#OrderDict type


from torch import nn
import torch
#creat a simple model
model = nn.Sequential(
 nn.Conv3d(1,16,kernel_size=1),
 nn.Conv3d(16,2,kernel_size=1))#tend to print the W of this layer
input = torch.randn([1,1,16,256,256])
if torch.cuda.is_available():
 print('cuda is avaliable')
 model.cuda()
 input = input.cuda()
#打印某一层的参数名
for name in model.state_dict():
 print(name)
#Then I konw that the name of target layer is '1.weight'

#schemem1(recommended)
print(model.state_dict()['1.weight'])

#scheme2
params = list(model.named_parameters())#get the index by debuging
print(params[2][0])#name
print(params[2][1].data)#data

#scheme3
params = {}#change the tpye of 'generator' into dict
for name,param in model.named_parameters():
params[name] = param.detach().cpu().numpy()
print(params['0.weight'])

#scheme4
for layer in model.modules():
if(isinstance(layer,nn.Conv3d)):
 print(layer.weight)

#打印每一层的参数名和参数值
#schemem1(recommended)
for name,param in model.named_parameters():
 print(name,param)

#scheme2
for name in model.state_dict():
 print(name)
 print(model.state_dict()[name])

来源:https://blog.csdn.net/weixin_44058333/article/details/92691656

标签:pytorch,模型,参数名,参数值
0
投稿

猜你喜欢

  • flask开启多线程的具体方法

    2023-03-10 06:30:50
  • Python 面向切面编程 AOP 及装饰器

    2021-05-07 14:16:36
  • python 共现矩阵的实现代码

    2021-12-22 14:42:33
  • 分享我们的select控件设计过程

    2009-06-16 18:04:00
  • 高手进阶:网页设计中的文字运用

    2008-10-05 08:58:00
  • 基于Python实现简易学生信息管理系统

    2021-04-07 23:19:49
  • 在python中读取和写入CSV文件详情

    2021-01-21 22:34:51
  • Django基础知识 URL路由系统详解

    2021-01-23 11:29:59
  • pyqt5 键盘监听按下enter 就登陆的实例

    2022-03-04 08:12:31
  • PHP基于openssl实现非对称加密代码实例

    2023-07-13 05:38:22
  • 解决编码问题:UnicodeDecodeError: 'utf-8' codec can't decod

    2023-03-25 02:45:59
  • js查找父节点的简单方法

    2023-09-11 01:12:42
  • 自动备份Oracle数据库

    2010-07-31 13:10:00
  • pytorch实现ResNet结构的实例代码

    2022-12-31 01:50:48
  • 如何对MySQL数据库表进行锁定

    2009-02-10 10:39:00
  • 基于numpy实现逻辑回归

    2023-06-21 10:04:25
  • python 使用 requests 模块发送http请求 的方法

    2021-06-02 17:29:19
  • ASP 3.0中的新特性

    2008-02-27 13:28:00
  • python基本语法练习实例

    2021-02-25 06:50:07
  • python 类相关概念理解

    2023-02-17 21:16:47
  • asp之家 网络编程 m.aspxhome.com