使用 SciPy 計算曼哈頓距離


曼哈頓距離,也稱為城市街區距離,計算為兩個向量間絕對差值的總和。它通常用於描述均勻網格上物件的向量,例如城市街區或棋盤格。以下是 n 元空間中計算曼哈頓距離的通用公式 −

$$\mathrm{D =\sum_{i=1}^{n}|r_i-s_i|}$$

其中:

si 和 ri 為資料點。

n 表示 n 元空間。

SciPy 為我們提供了一個名為cityblock 的函式,用於返回兩點間的曼哈頓距離。讓我們看看如何使用 SciPy 庫計算兩點間的曼哈頓距離−

示例

# Importing the SciPy library
from scipy.spatial import distance
# Defining the points
A = (1, 2, 3, 4, 5, 6)
B = (7, 8, 9, 10, 11, 12)
A, B

# Computing the Manhattan distance
manhattan_distance = distance.cityblock(A, B)
print('Manhattan Distance b/w', A, 'and', B, 'is: ', manhattan_distance)

輸出

Manhattan Distance b/w (1, 2, 3, 4, 5, 6) and (7, 8, 9, 10, 11, 12) is: 36

更新於: 14-12-2021

超過 1K 瀏覽

開啟你的 職業生涯

完成課程,獲得認證

開始學習
廣告