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

yipeiwu_com5年前Python基础

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])

以上这篇pytorch获取模型某一层参数名及参数值方式就是小编分享给大家的全部内容了,希望能给大家一个参考,也希望大家多多支持【听图阁-专注于Python设计】。

相关文章

Python中函数的基本定义与调用及内置函数详解

前言 函数function是python编程核心内容之一,也是比较重要的一块。首先我们要了解Python函数的基本定义: 函数是什么? 函数是可以实现一些特定功能的小方法或是小程序。...

Python基于更相减损术实现求解最大公约数的方法

Python基于更相减损术实现求解最大公约数的方法

本文实例讲述了Python基于更相减损术实现求解最大公约数的方法。分享给大家供大家参考,具体如下: 先从网上摘录一段算法的描述如下: 更相减损法:也叫 更相减损术,是出自《 九章算术》的...

20招让你的Python飞起来!

今天分享的这篇文章,文字不多,代码为主。绝对干货,童叟无欺,主要分享了提升 Python 性能的 20 个技巧,教你如何告别慢Python。原文作者 开元,全栈程序员,使用 Python...

整理Python中的赋值运算符

整理Python中的赋值运算符

下表列出了所有Python语言支持的赋值运算符。假设变量a持有10和变量b持有20,则:  例如: 试试下面的例子就明白了所有在Python编程语言可供选择的赋值运算符:...

Python3之手动创建迭代器的实例代码

迭代器即可以遍历诸如列表,字典及字符串等序列对象甚至自定义对象的对象,其本质就是记录迭代对象中每个元素的位置。迭代过程从第一个元素至最后一个元素,且过程不能回滚或反方向迭代。 两个基本方...