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使用微信itchat接口实现查看自己微信的信息功能详解

Python使用微信itchat接口实现查看自己微信的信息功能详解

本文实例讲述了Python使用微信itchat接口实现查看自己微信的信息功能。分享给大家供大家参考,具体如下: itchat是python的一个api,可以访问自己的微信信息,功能还蛮好...

python自动循环定时开关机(非重启)测试

做手机整机测试的,肯定有开关机的需求,关机,几分钟后再开机(一直循环操作测试,就是不能重启);这个需求在关机后就没有办法开机了,任何脚本命令都不行,除非做APP;重启功能的缺点是关机后就...

python 生成器和迭代器的原理解析

一、生成器简介 在python中,生成器是根据某种算法边循环边计算的一种机制。主要就是用于操作大量数据的时候,一般我们会将操作的数据读入内存中处理,可以计算机的内存是比较宝贵的资源,我...

Python遍历目录中的所有文件的方法

os.walk生成器 os.walk(PATH), PATH是个文件夹路径,当然可以用.或者../这样啦. 返回的是个三元元组为元素的列表, 每个元素代表了一个文件夹下的内容.第一个就是...

python操作CouchDB的方法

本文简单讲述了python操作CouchDB的方法,分享给大家供大家参考。具体方法如下: 1.安装python couchDb库: https://pypi.python.org/pyp...