torch 模型中相关参数param及child修改测试详解

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()会建立一个函数递归调用。

待更新。。。。。。

其他用到的在更新吧。

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值