how to calculate mahalanobis distance in pytorch?

4.7k views Asked by At

What is the most efficient way to calculate the mahalanobis distance: in pytorch?

enter image description here

1

There are 1 answers

0
Ivan On

Based on SciPy's implementation of the mahalanobis distance, you would do this in PyTorch. Assuming u and v are 1D and cov is the 2D covariance matrix.

def mahalanobis(u, v, cov):
    delta = u - v
    m = torch.dot(delta, torch.matmul(torch.inverse(cov), delta))
    return torch.sqrt(m)

Note: scipy.spatial.distance.mahalanobis takes in the inverse of the covariance matrix.