【问题标题】:PyTorch Conv2D returns non-zero output for an input tensor of zeros?PyTorch Conv2D 返回零输入张量的非零输出?
【发布时间】:2021-01-26 06:56:34
【问题描述】:

如果您将一个仅包含零的数组输入到 Conv2D 层,则输出也应仅包含零。在 TensorFlow 中,就是这种情况。但是,在 PyTorch 中,情况并非如此。这是一些非常简单的示例 Python 代码来演示这一点。为什么 PyTorch 在这种情况下会输出非零数字?

import torch
import numpy as np

image = np.zeros((3,3,3), dtype=np.float32)
batch = np.asarray([image])

a = torch.nn.Conv2d(3,3,1)
b = a(torch.tensor(batch).permute(0,3,1,2))

print(b.permute(0,2,3,1))

【问题讨论】:

    标签: tensorflow pytorch conv-neural-network


    【解决方案1】:

    Tensorflow 不同,PyTorch 使用非零值初始化偏差(参见source-code):

    def reset_parameters(self) -> None:
        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)
    

    【讨论】:

    • 谢谢。就这么简单。设置bias=0使输出为0。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2021-04-19
    • 1970-01-01
    • 2019-11-11
    • 2021-03-25
    • 2017-08-24
    • 1970-01-01
    • 2021-11-02
    相关资源
    最近更新 更多