Model中的参数操作详解
以如下模型代码为例:
class TestMLP(nn.Module):
def __init__(self, num_features, num_hidden1, num_hidden2, num_class):
super().__init__()
self.layers = nn.Sequential(
nn.Linear(num_features, num_hidden1),
nn.ReLU(),
nn.Linear(num_hidden1, num_hidden2),
nn.ReLU(),
nn.Linear(num_hidden2, num_class)
)
def forward(self, x):
x = self.layers(x)
return x
打印model可以看到:
TestMLP(
(layers): Sequential(
(0): Linear(in_features=64, out_features=32, bias=True)
(1): ReLU()
(2): Linear(in_features=32, out_features=64, bias=True)
(3): ReLU()
(4): Linear(in_features=64, out_features=3, bias=True)
)
)
1、named_parameters()
for name, param in model.named_parameters()
这个就是输出模型的名字和参数,很常见了。name的话就是每个层的名字,参数就很多了,大家可以自己试一下。
2、 parameters()
for param in model.parameters()
与1差不多,只不过仅有param没有了name。
3、model.children()
for child in model.children():
print(child)
该方法会遍历模型的子层,就跟树中的children是一个道理。
以我们上述的例子来看,它的输出就是整个Sequential层。如果我们定义模型的时候有两个Sequential,就会分别输出两个。所以一般的话使用model.children()会建立一个函数递归调用。
待更新。。。。。。
其他用到的在更新吧。