How to realize Mahalanobis distance function by Python
This article mainly introduces Python how to achieve Mahalanobis distance function, has a certain reference value, interested friends can refer to, I hope you can learn a lot after reading this article, the following let Xiaobian take you to understand.
Mahalanobis distance is different from Euclidean distance, as Baidu knows:
Mahalanobis distance (Mahalanobis distance) is proposed by Indian statistician P. C. Mahalanobis, which represents the distance between a point and a distribution. It is an effective method to calculate the similarity of two unknown sample sets. Unlike Euclidean distance, it takes into account the relationship between various characteristics (for example, a message about height brings a message about weight because the two are related) and is scale-invariant-independent, that is, independent of the measurement scale. For a multivariable vector with mean value μ and covariance matrix Σ, its Mahalanobis distance is sqrt ((x-μ)'Σ ^ (- 1) (x-μ)).
Therefore, the final definition of Mahalanobis distance is:
In the code above, the Mahalanobis distance formula is encapsulated as a Python function, and the copy can be used:
From numpy import * import numpydef get_mahalanobis (x, I, j): xT = x.T # find transpose D = numpy.cov (xT) # find covariance matrix invD = numpy.linalg.inv (D) # covariance inverse matrix assert 0