PyTorch Conv2D为0的输入张量返回非零输出



如果将仅由零组成的数组输入到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用非零值初始化偏差(请参阅源代码(:

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)