Get the App
SLTechnology News&Howtos  ›  Development  › 

How to realize Mahalanobis distance function by Python

Shulou Source: shulou.com Published: 2022-06-02 14:46:27 09月25日 Update

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

Tags: Mahalanobis between articles functions covariance mean sample point to matrix index information scale range different effective similar previous generation two representative value Apple Docker Huawei Linux macOS MariaDB Microsoft MySQL NVidia OPPO Reno macOS Docker Shulou Information Apple Huawei