pytorch获取模型某一层参数名及参数值方式
1、Motivation:
Iwannamodifythevalueofsomeparam;
Iwannacheckthevalueofsomeparam.
Theneededfunction:
2、state_dict()#generatortype
model.modules()#generatortype
named_parameters()#OrderDicttype
fromtorchimportnn
importtorch
#creatasimplemodel
model=nn.Sequential(
nn.Conv3d(1,16,kernel_size=1),
nn.Conv3d(16,2,kernel_size=1))#tendtoprinttheWofthislayer
input=torch.randn([1,1,16,256,256])
iftorch.cuda.is_available():
print('cudaisavaliable')
model.cuda()
input=input.cuda()
#打印某一层的参数名
fornameinmodel.state_dict():
print(name)
#ThenIkonwthatthenameoftargetlayeris'1.weight'
#schemem1(recommended)
print(model.state_dict()['1.weight'])
#scheme2
params=list(model.named_parameters())#gettheindexbydebuging
print(params[2][0])#name
print(params[2][1].data)#data
#scheme3
params={}#changethetpyeof'generator'intodict
forname,paraminmodel.named_parameters():
params[name]=param.detach().cpu().numpy()
print(params['0.weight'])
#scheme4
forlayerinmodel.modules():
if(isinstance(layer,nn.Conv3d)):
print(layer.weight)
#打印每一层的参数名和参数值
#schemem1(recommended)
forname,paraminmodel.named_parameters():
print(name,param)
#scheme2
fornameinmodel.state_dict():
print(name)
print(model.state_dict()[name])
以上这篇pytorch获取模型某一层参数名及参数值方式就是小编分享给大家的全部内容了,希望能给大家一个参考,也希望大家多多支持毛票票。
声明:本文内容来源于网络,版权归原作者所有,内容由互联网用户自发贡献自行上传,本网站不拥有所有权,未作人工编辑处理,也不承担相关法律责任。如果您发现有涉嫌版权的内容,欢迎发送邮件至:czq8825#qq.com(发邮件时,请将#更换为@)进行举报,并提供相关证据,一经查实,本站将立刻删除涉嫌侵权内容。