1

在神经网络中,我有一些 2D 特征图,其值介于 0 和 1 之间。对于这些图,我想根据每个坐标的值计算协方差矩阵。不幸的是,pytorch 没有.cov()像 numpy 那样的功能。所以我改写了以下函数:

def get_covariance(tensor):
    bn, nk, w, h = tensor.shape
    tensor_reshape = tensor.reshape(bn, nk, 2, -1)
    x = tensor_reshape[:, :, 0, :]
    y = tensor_reshape[:, :, 1, :]
    mean_x = torch.mean(x, dim=2).unsqueeze(-1)
    mean_y = torch.mean(y, dim=2).unsqueeze(-1)

    xx = torch.sum((x - mean_x) * (x - mean_x), dim=2).unsqueeze(-1) / (h * w - 1)
    xy = torch.sum((x - mean_x) * (y - mean_y), dim=2).unsqueeze(-1) / (h * w - 1)
    yx = xy
    yy = torch.sum((y - mean_y) * (y - mean_y), dim=2).unsqueeze(-1) / (h * w - 1)

    cov = torch.cat((xx, xy, yx, yy), dim=2)
    cov = cov.reshape(bn, nk, 2, 2)
    return cov

这是正确的方法吗?

编辑:

这是与numpy函数的比较:

a = torch.randn(1, 1, 64, 64)
a_numpy = a.reshape(1, 1, 2, -1).numpy()

torch_cov = get_covariance(a)
numpy_cov = np.cov(a_numpy[0][0])

torch_cov
tensor([[[[ 0.4964, -0.0053],
          [-0.0053,  0.4926]]]])

numpy_cov
array([[ 0.99295635, -0.01069122],
       [-0.01069122,  0.98539236]])

显然,我的值太小了 2 倍。为什么会这样?

Edit2:啊,我想通了。它必须除以(h*w/2 - 1):) 然后值匹配。

4

0 回答 0