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

相关文章

Centos5.x下升级python到python2.7版本教程

首先到官网下载python2.7.3版本,编译安装 复制代码 代码如下: $wget http://www.python.org/ftp/python/2.7.3/Python-2.7....

浅谈Django REST Framework限速

浅谈Django REST Framework限速

官方文档 settings.py配置 REST_FRAMEWORK = { 'DEFAULT_THROTTLE_CLASSES': ( 'rest_framework.t...

基于python的ini配置文件操作工具类

本文实例为大家分享了python的ini配置文件操作工具类的具体代码,供大家参考,具体内容如下 #!/usr/bin/env python # -*- coding: utf-8 -...

Python isinstance判断对象类型

复制代码 代码如下:if (typeof(objA) == typeof(String)) { //TODO } 在Python中只需要使用内置的函数isinstance,使用起来非常简...

Python 调用DLL操作抄表机

# -*- coding: GBK -*- from ctypes import * dll = windll.LoadLibrary('JBA188.dll') a = dll.tes...