最小化 Python 中两组点之间的总距离

Minimize total distance between two sets of points in Python

给定两组 n 维点 space,如何将点从一组映射到另一组,这样每个点只使用一次,并且点对之间的总欧氏距离最小化了吗?

例如,

import matplotlib.pyplot as plt
import numpy as np

# create six points in 2d space; the first three belong to set "A" and the
# second three belong to set "B"
x = [1, 2, 3, 1.8, 1.9, 3.4]
y = [2, 3, 1, 2.6, 3.4, 0.4]

colors = ['red'] * 3 + ['blue'] * 3

plt.scatter(x, y, c=colors)
plt.show()

所以在上面的例子中,目标是将每个红点映射到一个蓝点,这样每个蓝点只使用一次,并且点之间的距离总和最小。

我遇到了 this question 这有助于解决问题的第一部分——使用 scipy.spatial.distance.cdist()函数。

从那里,我可能可以测试每一行中单个元素的每个排列,并找到最小值。

我想到的应用程序涉及相当少量的 3 维数据点 space,因此蛮力方法可能没问题,但我想我会检查一下是否有人知道首先是更有效或更优雅的解决方案。

有一个已知的算法,The Hungarian Method For Assignment,它的运行时间为 O(n3)

在SciPy中,您可以在scipy.optimize.linear_sum_assignment

中找到实现

将一组点的元素分配(映射)到另一组点的元素的示例,使得总欧氏距离最小化。

import numpy as np
import matplotlib.pyplot as plt
from scipy.spatial.distance import cdist
from scipy.optimize import linear_sum_assignment

np.random.seed(100)

points1 = np.array([(x, y) for x in np.linspace(-1,1,7) for y in np.linspace(-1,1,7)])
N = points1.shape[0]
points2 = 2*np.random.rand(N,2)-1

C = cdist(points1, points2)

_, assigment = linear_sum_assignment(C)

plt.plot(points1[:,0], points1[:,1],'bo', markersize = 10)
plt.plot(points2[:,0], points2[:,1],'rs',  markersize = 7)
for p in range(N):
    plt.plot([points1[p,0], points2[assigment[p],0]], [points1[p,1], points2[assigment[p],1]], 'k')
plt.xlim(-1.1,1.1)
plt.ylim(-1.1,1.1)
plt.axes().set_aspect('equal')