Pytorch correaltion matrix of batches

Viewed 186

I have a tensor input of dimensions (B,C,H,W) and I would like to find a correlation matrix of the input. The code I am using is :

def corr(x):
    """
    x: [B, C, H, W]
    """

    # [B, C, H, W] -> [B, C, H * W]
    x = x.view((x.size(0), x.size(1), -1))

    # estimated covariance
    x = x - x.mean(dim=-1, keepdim=True)
    factor = 1 / (x.shape[-1] - 1)
    
    cov = factor * (x @ x.transpose(-1, -2))
    return torch.div(cov,torch.diagonal(cov, dim1=-2, dim2=-1))

So I rechecked myself and it looks like I am getting good results for the cov variable in a function but when I try to normalize it to get the correlation, the result's range is very strange, there are values above 1 and below -1, and overall the solution does not seem to be right. Any suggestions on how to solve the problem?

0 Answers
Related