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

yipeiwu_com6年前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设计】。

相关文章

python3中的md5加密实例

在python3的标准库中,已经移除了md5,而关于hash加密算法都放在hashlib这个标准库中,如SHA1、SHA224、SHA256、SHA384、SHA512和MD5算法等。...

python实现自动登录人人网并采集信息的方法

本文实例讲述了python实现自动登录人人网并采集信息的方法。分享给大家供大家参考。具体实现方法如下: #!/usr/bin/python # -*- coding: utf-8 -...

python生成器表达式和列表解析

绝大多数情况下,遍历一个集合都是为了对元素应用某个动作或是进行筛选。如果看过本文的第二部分,你应该还记得有内建函数map和filter提供了这些功能,但Python仍然为这些操作提供了语...

Python实现直方图均衡基本原理解析

Python实现直方图均衡基本原理解析

1. 基本原理 通过一个变换,将输入图像的灰度级转换为`均匀分布`,变换后的灰度级的概率密度函数为 $$P_s(s) = \frac{1}{L-1}$$ 直方图均衡的变换为 $$s...

python递归实现快速排序

快速排序(QuickSort)是对冒泡排序的一种改进: 基本思想: 通过一趟排序将要排序的数据分割成独立的两部分,其中一部分的所有数据都比另外一部分的所有数据都要小,然后再按此方法对这两...