# 在 Python 中計算馬氏距離

Muhammad Maisam Abbas 2023年1月30日

## 使用 Python 中 `scipy.spatial.distance` 庫中的 `cdist()` 函式計算馬氏距離

``````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)
``````

``````[3.63263583 2.59094773 1.97370848 1.97370848 2.177978   3.04256456
3.04256456 1.54080605 2.58298363]
``````

## 在 Python 中使用 `numpy.einsum()` 方法計算馬氏距離

``````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)
``````

``````[3.63263583 2.59094773 1.97370848 1.97370848 2.177978   3.04256456
3.04256456 1.54080605 2.58298363]
``````

Maisam is a highly skilled and motivated Data Scientist. He has over 4 years of experience with Python programming language. He loves solving complex problems and sharing his results on the internet.