我希望能够找到xy平面中两组点之间的最小距离。假设第一组点A,有9个点,第二组点B,有3个点。我想找到将集合A中的每个点连接到集合B中的点的最小总距离。显然,将存在一些重叠,甚至可能在集合B中没有链接的某些点。但是集合A中的所有点必须有1个且只有1个链接从它到集合B中的某个点。
如果两个集合的点数相等,我找到了解决这个问题的方法,这里是代码:
import random
import numpy as np
import matplotlib.pyplot as plt
from scipy.spatial.distance import cdist
from scipy.optimize import linear_sum_assignment
points1 = np.array([(x, y) for x in np.linspace(-1,1,3) \
for y in np.linspace(-1,1,3)])
N = points1.shape[0]
points2 = 2*np.random.rand(N,2)-1
cost12 = cdist(points1, points2)
row_ind12, col_ind12 = linear_sum_assignment(cost12)
plt.plot(points1[:,0], points1[:,1], 'b*')
plt.plot(points2[:,0], points2[:,1], 'rh')
for i in range(N):
plt.plot([points1[i,0], points2[col_ind12[i],0]], [points1[i,1],
points2[col_ind12[i],1]], 'k')
plt.show()
答案 0 :(得分:2)
函数scipy.cluster.vq.vq
可以满足您的需求。
以下是代码的修改版本,用于演示vq
:
import numpy as np
from scipy.cluster.vq import vq
import matplotlib.pyplot as plt
# `points1` is the set A described in the question.
points1 = np.array([(x, y) for x in np.linspace(-1,1,3)
for y in np.linspace(-1,1,3)])
# `points2` is the set B. In this example, there are 5 points in B.
N = 5
np.random.seed(1357924)
points2 = 2*np.random.rand(N, 2) - 1
# For each point in points1, find the closest point in points2:
code, dist = vq(points1, points2)
plt.plot(points1[:,0], points1[:,1], 'b*')
plt.plot(points2[:,0], points2[:,1], 'rh')
for i, j in enumerate(code):
plt.plot([points1[i,0], points2[j,0]],
[points1[i,1], points2[j,1]], 'k', alpha=0.4)
plt.grid(True, alpha=0.25)
plt.axis('equal')
plt.show()
该脚本生成以下图: