Pytorch 参数管理
import torch
import torch.nn as nn
from torch.nn.parameter import Parameter
class model(torch.nn.Module):
def __init__(self,in_put,h,out_put):
'''自定义模型的初始化'''
super(model,self).__init__()
self.linear1=torch.nn.Linear(in_put,h)
self.linear2=torch.nn.Linear(h,out_put)
def forward(self,x):
'''前向传播'''
h_relu = self.linear1(x).clamp(min=0)
y_pred = self.linear2(h_relu)
return y_pred
model = model(10,5,2)
x=torch.empty(2,10)
y=model(x)
print(model.parameters) #打印每层简化参数
print(list(model.parameters()))
print(list(model.named_parameters())) #相比model.parameters() ,model.named_parameters()会多打印出名字
'''
2、model.named_parameters、打印每一次迭代元素的名字和param,以及更改参数(W B)的requires_grad的属性
'''
for name, param in model.named_parameters():
print(name,param.shape,param.requires_grad)
#param.requires_grad=False #更改requires_grad的属性
model.state_dict()#
''' model.state_dict() 以字典的形式 包含所有parameters 的参数 权重 和偏置
state_dict是基本上其映射的字典nn.Parameter的网络的对象的值
'''
for param in model.state_dict():
print(param, "\t", model.state_dict()[param].size())
model.state_dict().keys() 打印每层参数(权重和偏置)的名称
odict_keys(['linear2.weight', 'linear2.bias'])
model.state_dict()['linear2.bias'].shape
model.state_dict().values()