Calculating Mahalanobis distance in Python
This tutorial will show you how to find the Mahalanobis distance between two NumPy arrays in Python.
Use the function scipy.spatial.distance
in the Python library cdist()
to calculate the Mahalanobis distance
The Mahalanobis distance is a measure of the distance between a point and a distribution. If we want to find the Mahalanobis distance between two arrays, we can use the function scipy.spatial.distance
from the library in Python cdist()
. cdist()
The function calculates the distance between two sets. We can specify in the input parameter mahalanobis
to find the Mahalanobis distance. Refer to the following code example.
import numpy as np
from scipy.spatial.distance import cdist
x = np.array([[[1, 2, 3], [3, 4, 5], [5, 6, 7]], [[5, 6, 7], [7, 8, 9], [9, 0, 1]]])
i, j, k = x.shape
xx = x.reshape(i, j * k).T
y = np.array([[[8, 7, 6], [6, 5, 4], [4, 3, 2]], [[4, 3, 2], [2, 1, 0], [0, 1, 2]]])
yy = y.reshape(i, j * k).T
results = cdist(xx, yy, "mahalanobis")
results = np.diag(results)
print(results)
Output:
[3.63263583 2.59094773 1.97370848 1.97370848 2.177978 3.04256456
3.04256456 1.54080605 2.58298363]
cdist()
We computed and stored the Mahalanobis distance between arrays x
and
using the function in the code above . We first created two arrays using the function. We then reshaped both arrays and saved the transpose in new arrays and . We then passed these new arrays to the function, specifying in the parameter using .y
np.array()
xx
yy
cdist()
cdist(xx,yy,'mahalanobis')
mahalanobis
numpy.einsum()
Calculate Mahalanobis distance
in Python using the method
We can also calculate the Mahalanobis distance between two arrays using numpy.einsum()
the methodnumpy.einsum()
. The method is used to evaluate the Einstein summation convention for the input arguments.
import numpy as np
x = np.array([[[1, 2, 3], [3, 4, 5], [5, 6, 7]], [[5, 6, 7], [7, 8, 9], [9, 0, 1]]])
i, j, k = x.shape
xx = x.reshape(i, j * k).T
y = np.array([[[8, 7, 6], [6, 5, 4], [4, 3, 2]], [[4, 3, 2], [2, 1, 0], [0, 1, 2]]])
yy = y.reshape(i, j * k).T
X = np.vstack([xx, yy])
V = np.cov(X.T)
VI = np.linalg.inv(V)
delta = xx - yy
results = np.sqrt(np.einsum("nj,jk,nk->n", delta, VI, delta))
print(results)
Output:
[3.63263583 2.59094773 1.97370848 1.97370848 2.177978 3.04256456
3.04256456 1.54080605 2.58298363]
We passed the array to np.vstack()
the function and stored the values in X
. After that, we passed X
the transpose of to np.cov()
the function and stored the result in V
. Then we calculated V
the multiplicative inverse of the matrix and stored the result in VI
. We calculated the difference between xx
and yy
and stored the result in delta
. Finally, we results = np.sqrt(np.einsum('nj,jk,nk->n', delta, VI, delta))
calculated and stored the Mahalanobis distance between x
and using .y
For reprinting, please send an email to 1244347461@qq.com for approval. After obtaining the author's consent, kindly include the source as a link.
Related Articles
Implementing the ReLU function in Python
Publish Date:2025/05/05 Views:177 Category:Python
-
This tutorial will discuss the Relu function and how to implement it in Python. ReLU function Relu Functions are the foundation of machine learning and are essential when using deep learning. ReLU The term is Rectified Linear Unit an acrony
Killing a Python process
Publish Date:2025/05/05 Views:152 Category:Python
-
When programming in Python, sometimes our program gets stuck in an infinite loop. In this case, we need to terminate the program manually. This article will discuss different ways to kill a Python process. Killing a Python process using a k
Get file extension in Python
Publish Date:2025/05/05 Views:63 Category:Python
-
This tutorial shows how to get the file extension from a file name in Python. os.path Extract extension from file using module in Python The Python module os.path pre-makes useful utility functions for manipulating operating system file pat
Read the first line of a file in Python
Publish Date:2025/05/05 Views:192 Category:Python
-
In Python, we have built-in functions to handle different file operations. A text file contains a sequence of strings where each line \n is terminated by a newline character. In this tutorial, we will learn how to read the first line of a t
Reading binary files in Python
Publish Date:2025/05/05 Views:119 Category:Python
-
The program or internal processor interprets the binary file. It contains bytes as content. When we read a binary file, an bytes object of type is returned. open() Read a binary file using the function in Python In Python, we have open() th
Writing bytes to a file in Python
Publish Date:2025/05/05 Views:193 Category:Python
-
In this tutorial, we will look at how to write bytes to a binary file in Python. Binary files contain strings of type bytes. When we read a binary file, an object of type bytes is returned. In Python, bytes are represented by hexadecimal nu
Python get file name without extension from path
Publish Date:2025/05/05 Views:81 Category:Python
-
This tutorial will demonstrate various ways to get the file name without extension from a file path in Python. Suppose our goal is to get the file name from a list of file paths that are in the form of strings, such as from the path Desktop
Calculate the time difference between two time strings in Python
Publish Date:2025/05/05 Views:182 Category:Python
-
Sometimes we have to deal with date and time related problems in programming. In Python, date and time are not data types themselves. Despite this, Python provides a large number of functions and libraries to help deal with such problems. O
Optional parameters in Python
Publish Date:2025/05/05 Views:151 Category:Python
-
In Python, there is something called default arguments. It is also called optional parameters or optional arguments in python. Parameters refer to the inputs of a function. Functions with multiple optional parameters in Python Whenever you