SciPy - maxdists() 方法



SciPy maxdists() 方法引用模組 “from scipy.spatial.distance import pdist”,該模組允許函式 pdist() 計算給定集合中點之間的成對距離。

該函式在 scipy 中沒有任何直接方法。如果使用者想查詢最大的成對距離,他們可能會更喜歡返回所有成對距離的 pdist() 方法。

語法

其語法如下 −

pdist(point)

引數

此方法只接受一個引數 −

  • point: 這是一個使用 array() 儲存陣列點集的簡單變數。

返回值

此方法返回整數和浮點數的 nd 陣列值。

示例 1

以下是 SciPy maxdists() 方法,它分別使用 pdist() 和 max() 函式說明成對和最大距離。

import numpy as np
from scipy.spatial.distance import pdist

# input data
point = np.array([
    [0, 0],
    [1, 1],
    [2, 2],
    [3, 3],
    [4, 4]
])

# pairwise distances
dist = pdist(point)

# maximum distance
max_dist = np.max(dist)

print("The result of pairwise distances:", dist)
print("The result of maximum distance:", max_dist)

輸出

上述程式碼產生以下輸出 −

The result of pairwise distances: [1.41421356 2.82842712 4.24264069 5.65685425 1.41421356 2.82842712
 4.24264069 1.41421356 2.82842712 1.41421356]
The result of maximum distance: 5.656854249492381

示例 2

此程式執行與 示例 1 相同的計算,但這裡你將得到不同距離度量的結果。

import numpy as np
from scipy.spatial.distance import pdist

# input data in the form of array of points
point = np.array([
    [0, 0],
    [1, 1],
    [2, 2],
    [3, 3],
    [4, 4]
])

# calculate pairwise distances using Manhattan (Cityblock) distance
dist = pdist(point, metric='cityblock')

# find the maximum distance
max_dist = np.max(dist)

print("Pairwise distances (Manhattan):", dist)
print("Maximum distance (Manhattan):", max_dist)

輸出

上述程式碼產生以下輸出 −

Pairwise distances (Manhattan): [2. 4. 6. 8. 2. 4. 6. 2. 4. 2.]
Maximum distance (Manhattan): 8.0
scipy_reference.htm
廣告
© . All rights reserved.