Giải sử
a = (3, 7, 1)
b = (2, 5, 5)
$$d_{\text{Manhattan}}(\mathbf{a}, \mathbf{b}) = \sum_{i=1}^{n} \left| x_i - y_i \right|$$
Ví dụ$$d_{\text{Manhattan}}(\mathbf{a}, \mathbf{b}) = |3-2| + |7-5| + |1-5| = 7$$
$$d_{\text{Euclidean}}(\mathbf{a}, \mathbf{b}) = \sqrt{\sum_{i=1}^{n} (x_i - y_i)^2}$$
Ví dụ$$d_{\text{Euclidean}}(\mathbf{a}, \mathbf{b}) = \sqrt{(3 - 2)^2 + (7-5)^2 + (1-5)^2} = \sqrt{21} \approx 4.58$$
$$d_{\text{Minkowski}}(\mathbf{a}, \mathbf{b}) = \sqrt[p]{\left( \sum_{i=1}^{n} |x_i - y_i|^p \right)}, \quad p \ge 1$$
Ví dụ$$d_{\text{Minkowski}}(\mathbf{a}, \mathbf{b}) = \sqrt[3]{\left(|3 - 2|^3 + |7-5|^3 + |1-5|^3\right)} = \sqrt[3]{73} \approx 4.18 $$
from scipy.spatial.distance import minkowski, euclidean, cityblock
a = [3, 7, 1]
b = [2, 5, 5]
print('manhattan distance', cityblock(a, b))
print('euclidean distance', euclidean(a, b))
print('minkowski distance', minkowski(a, b, p = 3))
NaN-Euclidean distance được sử dụng khi dữ liệu có giá trị thiếu (NaN). Khoảng cách chỉ được tính trên các chiều mà cả hai vector đều có giá trị, sau đó được chuẩn hoá.
Ký hiệuGiả sử hai vector đặc trưng:
$$ \mathbf{x} = (x_1, x_2, \dots, x_d), \quad \mathbf{y} = (y_1, y_2, \dots, y_d) $$
Tập các chiều hợp lệ:$$S = \{\, i \mid x_i \neq \text{NaN} \ \text{and} \ y_i \neq \text{NaN} \,\}$$
Công thức$$d_{\text{nan-euclidean}}(\mathbf{x}, \mathbf{y}) = \sqrt{ \frac{d}{|S|} \sum_{i \in S} (x_i - y_i)^2 }$$
Trong đó:Nếu |S| = 0 thì khoảng cách không xác định.
Ví dụ$$\mathbf{x} = (2,\ \text{NaN},\ 5,\ 1)$$
$$\mathbf{y} = (4,\ 3,\ 5,\ \text{NaN})$$
$$d(x,y) = \sqrt{\frac{4}{2}((3-4)^2+(5-5)^2)} = 2\sqrt{2}$$
from sklearn.metrics import nan_euclidean_distances
import numpy as np
X = [
[2, np.nan, 5, 1],
[4, 3, 5, np.nan]
]
nan_euclidean_distances(X)