从一个点到所有其他点的距离总和

时间:2018-01-12 04:57:01

标签: python numpy scipy euclidean-distance pdist

我有两个列表

available_points = [[2,3], [4,5], [1,2], [6,8], [5,9], [51,35]]

solution = [[3,5], [2,1]]

我正在尝试弹出 available_points中的一个点,追加到solution,其中欧几里德距离的总和与该点相同,solution中的所有点都是最大的。

所以,我会得到这个

solution = [[3,5], [2,1], [51,35]]

我能够选择这样的最初2个最远点,但不知道如何继续。

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

available_points = np.array([[2,3], [4,5], [1,2], [6,8], [5,9], [51,35]])

D = squareform(pdist(available_points)
I_row, I_col = np.unravel_index(np.argmax(D), D.shape)
solution = available_points[[I_row, I_col]]

给了我

solution = array([[1, 2], [51, 35]])

4 个答案:

答案 0 :(得分:2)

因为您标记了numpy

import numpy as np 

solution=np.array(solution)
available_points=np.array(available_points)
l=[]
for x in solution:
    l.append(np.linalg.norm(available_points-x, keepdims=True,axis=1))


np.append(solution,[available_points[np.argmax(np.array(l).sum(0))]],axis=0)
Out[237]: 
array([[ 3,  5],
       [ 2,  1],
       [51, 35]])

答案 1 :(得分:2)

您可以使用cdist -

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

In [2]: max_pt=available_points[cdist(available_points, solution).sum(1).argmax()]

In [3]: np.vstack((solution, max_pt))
Out[3]: 
array([[ 3,  5],
       [ 2,  1],
       [51, 35]])

答案 2 :(得分:1)

您可以使用max函数在" available_points'中找到最大值。列表&然后追加最多的' available_points'列出解决方案'清单! 我还附上了输出的截图!

available_points = [[2,3], [4,5], [1,2], [6,8], [5,9], [51,35]];
solution = [[3,5], [2,1]]
solution.append(max(available_points));
print(solution);

output

答案 3 :(得分:0)

我使用cdist

计算出来了
from scipy.spatial.distance import cdist

d = cdist(solution, available_points)

distances = []

for q in range(len(available_points)):
    y = d[:,q]
    distances.append(sum(y))

# Largest Distance
max_point = available_points[distances.index(max(distances))]

# Update datasets
solution = np.append(solution, [max_point], axis=0)
universe = np.delete(available_points, max_index, 0)