pytorch中的model.named_parameters()与model.parameters()

参考链接:https://www.cnblogs.com/yqpy/p/12585331.html

model.named_parameters()

迭代打印model.named_parameters()将会打印每一次迭代元素的名字和param。

model = DarkNet([1, 2, 8, 8, 4])
for name, param in model.named_parameters():
    print(name,param.requires_grad)
    param.requires_grad = False

输出结果为

conv1.weight True
bn1.weight True
bn1.bias True
layer1.ds_conv.weight True
layer1.ds_bn.weight True
layer1.ds_bn.bias True
layer1.residual_0.conv1.weight True
layer1.residual_0.bn1.weight True
layer1.residual_0.bn1.bias True
layer1.residual_0.conv2.weight True
layer1.residual_0.bn2.weight True
layer1.residual_0.bn2.bias True
layer2.ds_conv.weight True
layer2.ds_bn.weight True
layer2.ds_bn.bias True
layer2.residual_0.conv1.weight True
layer2.residual_0.bn1.weight True
layer2.residual_0.bn1.bias True
....

并且可以更改参数的可训练属性,第一次打印是True,这是第二次,就是False了

model.parameters()

迭代打印model.parameters()将会打印每一次迭代元素的param而不会打印名字,这是它和named_parameters的区别,两者都可以用来改变requires_grad的属性。

for index, param in enumerate(model.parameters()):
    print(param.shape)

输出结果为

torch.Size([32, 3, 3, 3])
torch.Size([32])
torch.Size([32])
torch.Size([64, 32, 3, 3])
torch.Size([64])
torch.Size([64])
torch.Size([32, 64, 1, 1])
torch.Size([32])
torch.Size([32])
torch.Size([64, 32, 3, 3])
torch.Size([64])
torch.Size([64])
torch.Size([128, 64, 3, 3])
torch.Size([128])
torch.Size([128])
torch.Size([64, 128, 1, 1])
torch.Size([64])
torch.Size([64])
torch.Size([128, 64, 3, 3])
torch.Size([128])
torch.Size([128])
torch.Size([64, 128, 1, 1])
torch.Size([64])
torch.Size([64])
torch.Size([128, 64, 3, 3])
torch.Size([128])
torch.Size([128])
torch.Size([256, 128, 3, 3])
torch.Size([256])
torch.Size([256])
torch.Size([128, 256, 1, 1])
....

将两者结合进行迭代,同时具有索引,网络层名字及param

	for index, (name, param) in zip(enumerate(model.parameters()), model.named_parameters()):
		print(index[0])
		print(name, param.shape)

输出结果为

0
conv1.weight torch.Size([32, 3, 3, 3])
1
bn1.weight torch.Size([32])
2
bn1.bias torch.Size([32])
3
layer1.ds_conv.weight torch.Size([64, 32, 3, 3])
4
layer1.ds_bn.weight torch.Size([64])
5
layer1.ds_bn.bias torch.Size([64])
6
layer1.residual_0.conv1.weight torch.Size([32, 64, 1, 1])
7
layer1.residual_0.bn1.weight torch.Size([32])
8
layer1.residual_0.bn1.bias torch.Size([32])
9
layer1.residual_0.conv2.weight torch.Size([64, 32, 3, 3])

 

你可能感兴趣的:(深度学习,神经网络,深度学习,pytorch,神经网络)