1

Within a neural network, I have some 2D feature maps with values between 0 and 1. For these maps, I want to calculate the covariance matrix based on the values at each coordination. Unfortunately, pytorch has no .cov() function like in numpy. So I wrote the following function instead:

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

Is that the correct way to do it?

Edit:

Here is a comparison with the numpy function:

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]])

Apparently, my values are too small by a factor of 2. Why could that be?

Edit2: Ahhh I figured it out. It has to be divided by (h*w/2 - 1) :) Then the values match.

spadel
  • 998
  • 2
  • 16
  • 40

0 Answers0