SciPy for computeing Distance between points
SciPy defines some useful functions for computing distances between sets of points.
1、The function scipy.spatial.distance.pdist
computes the distance between all pairs of points in a given set:
import numpy as np from scipy.spatial.distance import pdist, squareform # Create the following array where each row is a point in 2D space: # [[0 1] # [1 0] # [2 0]] x = np.array([[0, 1], [1, 0], [2, 0]]) print(x) # Compute the Euclidean distance between all rows of x. # d[i, j] is the Euclidean distance between x[i, :] and x[j, :], # and d is the following array: # [[ 0. 1.41421356 2.23606798] # [ 1.41421356 0. 1. ] # [ 2.23606798 1. 0. ]] d = squareform(pdist(x, 'euclidean')) print(d)
array=
[dx1(row1),x1(row1),dx1(row1),x1(row2),dx1(row1),x1(row3)]
[dx1(row2),x1(row1),dx1(row2),x1(row2),dx1(row2),x1(row3)]
[dx1(row3),x1(row1),dx1(row3),x1(row2),dx1(row3),x1(row3)]
2、
常見的歐氏距離計算:
-
In [1]: from scipy.spatial.distance import cdist
-
...: import numpy as np
-
...: x1 =np.array([(1,3),(2,4),(5,6)])
-
...: x2 =[(3,7),(4,8),(6,9)]
-
...: cdist(x1,x2,metric='euclidean')
-
...:
-
Out[1]:
-
array([[ 4.47213595, 5.83095189, 7.81024968],
-
[ 3.16227766, 4.47213595, 6.40312424],
-
[ 2.23606798, 2.23606798, 3.16227766]])
解析上述計算過程:結果陣列中的第一行資料表示的是x1陣列中第一個元素點與x2陣列中各個元素點的距離,計算兩點之間的距離
array=
[dx1(row1),x2(row1),dx1(row1),x2(row2),dx3(row1),x3(row3)]
[dx1(row2),x2(row1),dx1(row2),x2(row2),dx3(row2),x3(row3)]
[dx1(row3),x2(row1),dx1(row3),x2(row2),dx3(row3),x3(row3)]
以點(1,3)與(3,7)點的距離為例:
-
In [2]: np.power((1-3)**2 +(3-7)**2,1/2)
-
Out[2]: 4.4721359549995796
--------------------- 本文來自 每天進步一點點2017 的CSDN 部落格 ,全文地址請點選:https://blog.csdn.net/kancy110/article/details/75675574?utm_source=copy