gpt4 book ai didi

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

转载 作者:太空狗 更新时间:2023-10-30 00:34:45 25 4
gpt4 key购买 nike

给定 n 维空间中的两组点,如何将一组点映射到另一组点,使得每个点仅使用一次,并且两对点之间的总欧氏距离最小化?

例如,

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

example of point distance minimization problem

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

我遇到了 this question这有助于解决问题的第一部分——使用 scipy.spatial.distance.cdist() 函数计算跨越 集的所有点对之间的距离。

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

我想到的应用程序涉及 3 维空间中相当少的数据点,因此蛮力方法可能没问题,但我想我会先看看是否有人知道更有效或更优雅的解决方案.

最佳答案

将一组点的元素分配(映射)到另一组点的元素的示例,这样欧几里得距离之和最小。

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

enter image description here

关于python - 最小化Python中两组点之间的总距离,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39016821/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com