2

我希望能够找到 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()

4

1 回答 1

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

该脚本生成以下图:

阴谋

于 2018-04-12T22:00:30.603 回答