【问题标题】:Follow-up to "In PyTorch how are layer weights and biases initialized by default?"“在 PyTorch 中,默认情况下如何初始化层权重和偏差?”的后续行动
【发布时间】:2021-11-08 14:30:15
【问题描述】:

this question 投票最多的答案中,它说:

大多数层都是使用Kaiming Uniform 方法初始化的。示例层包括 Linear、Conv2d、RNN 等。

我实际上在想:从哪里知道这个?例如,我想知道 PyTorch 1.9.0 的 torch.nn.Conv2dtorch.nn.BatchNorm2d 的默认初始化。对于torch.nn.Linear,我找到了答案here(来自上述问题的第二个答案)。

【问题讨论】:

    标签: deep-learning neural-network pytorch


    【解决方案1】:

    nn.Conv1dnn.Conv2dnn.Conv3d 等卷积模块继承自 _ConvNd 类。这个类有一个reset_parameters 函数,就像nn.Linear 一样实现:

    def reset_parameters(self) -> None:
        # Setting a=sqrt(5) in kaiming_uniform is the same as initializing with
        # uniform(-1/sqrt(k), 1/sqrt(k)), where k = weight.size(1) * prod(*kernel_size)
        # For more details see: 
        # https://github.com/pytorch/pytorch/issues/15314#issuecomment-477448573
        init.kaiming_uniform_(self.weight, a=math.sqrt(5))
        if self.bias is not None:
            fan_in, _ = init._calculate_fan_in_and_fan_out(self.weight)
            bound = 1 / math.sqrt(fan_in)
            init.uniform_(self.bias, -bound, bound)
    

    至于nn.BatchNorm2d,它有reset_parametersreset_running_stats功能:

    def reset_parameters(self) -> None:
        self.reset_running_stats()
        if self.affine:
            init.ones_(self.weight)
            init.zeros_(self.bias)
    
    def reset_running_stats(self) -> None:
        if self.track_running_stats:
            # running_mean/running_var/num_batches... are registered at runtime depending
            # if self.track_running_stats is on
            self.running_mean.zero_()  # type: ignore[operator]
            self.running_var.fill_(1)  # type: ignore[operator]
            self.num_batches_tracked.zero_()  # type: ignore[operator]
    

    【讨论】:

    • 感谢这个有用的答案!实际上我也一直在 GitHub 上搜索 reset_parameters 函数,但我错过了在 GitHub 上有一个名为 conv.py 的单独文件。我对偏差的初始化有一个问题,因为它在第 4 页的论文“深入研究整流器:在 ImageNet 分类上超越人类水平的性能”中说:“[...] 我们还初始化 b = 0。”但这并不是针对偏差项完成的,因为代码建议您共享。你知道为什么不吗?
    • 我想你会发现这个other question 很有趣。它讨论了两种初始化方法之间的区别。
    猜你喜欢
    • 2018-07-09
    • 2018-12-31
    • 1970-01-01
    • 1970-01-01
    • 2018-09-23
    • 1970-01-01
    • 2018-09-01
    • 2018-06-23
    • 1970-01-01
    相关资源
    最近更新 更多