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

from:http://cs231n.github.io/python-numpy-tutorial/

2、

常见的欧氏距离计算:

  1. In [1]: from scipy.spatial.distance import cdist

  2. ...: import numpy as np

  3. ...: x1 =np.array([(1,3),(2,4),(5,6)])

  4. ...: x2 =[(3,7),(4,8),(6,9)]

  5. ...: cdist(x1,x2,metric='euclidean')

  6. ...:

  7. Out[1]:

  8. array([[ 4.47213595, 5.83095189, 7.81024968],

  9. [ 3.16227766, 4.47213595, 6.40312424],

  10. [ 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)点的距离为例:

  1. In [2]: np.power((1-3)**2 +(3-7)**2,1/2)

  2. Out[2]: 4.4721359549995796

--------------------- 本文来自 每天进步一点点2017 的CSDN 博客 ,全文地址请点击:https://blog.csdn.net/kancy110/article/details/75675574?utm_source=copy

from :https://blog.csdn.net/kancy110/article/details/75675574 

©️2020 CSDN 皮肤主题: 书香水墨 设计师:CSDN官方博客 返回首页