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

相关文章

深入理解Javascript中的this关键字

自从接触javascript以来,对this参数的理解一直是模棱两可。虽有过深入去理解,但却也总感觉是那种浮于表面,没有完全理清头绪。 但对于this参数,确实会让人产生很多误解。那么t...

Python面向对象类继承和组合实例分析

本文实例讲述了Python面向对象类继承和组合。分享给大家供大家参考,具体如下: 在python3中所有类默认继承object,凡是继承了object的类都成为新式类,以及该子类的子类P...

基于MTCNN/TensorFlow实现人脸检测

基于MTCNN/TensorFlow实现人脸检测

人脸检测方法有许多,比如opencv自带的人脸Haar特征分类器和dlib人脸检测方法等。对于opencv的人脸检测方法,有点是简单,快速;存在的问题是人脸检测效果不好。正面/垂直/光线...

Python基于Opencv来快速实现人脸识别过程详解(完整版)

Python基于Opencv来快速实现人脸识别过程详解(完整版)

前言 随着人工智能的日益火热,计算机视觉领域发展迅速,尤其在人脸识别或物体检测方向更为广泛,今天就为大家带来最基础的人脸识别基础,从一个个函数开始走进这个奥妙的世界。 首先看一下本实验需...

在Pycharm中修改文件默认打开方式的方法

在Pycharm中修改文件默认打开方式的方法

新下载了一个Pycharm,建了个小demo,期间产生了一个sqlite3文件,由于是第一次打开,就弹出选择打开方式的对话框,手一块直接点了个Text,然后就乱码了: 那我们不小心操作...