【Pytorch进阶】Pytorch冻结部分层的参数

1 作用

optimizer = optim.Adam(filter(lambda p: p.requires_grad, self.parameters()), lr=lr, amsgrad=True)
# 
filter(lambda p: p.requires_grad, self.parameters())

在读代码时遇到了上述的情景,记录一下作用。上述代码的作用主要是用来在训练中冻结神经网络中的一些层。其中,self.parameters是存储神经网络中间产数矩阵的变量,lambda是函数,filter是过滤函数。

filter()函数接收两个参数,第一个为函数,第二个为序列,序列的每个元素作为参数传递给函数进行判断,然后返回 True 或 False,最后将返回 True 的元素放到新列表中。

即该函数将requires_grad = True的参数传入优化器进行反向传播,requires_grad = False的则被过滤掉。

2 参考文献

[1]python filter(lambda x: x.requires_grad, parameters)什么意思
[2]Pytorch冻结部分层的参数

猜你喜欢

转载自blog.csdn.net/zfhsfdhdfajhsr/article/details/128929378