【问题标题】:Keep a Numpy array sort unchanged when it gets shuffled and noisy in an iteration当 Numpy 数组在迭代中被打乱和嘈杂时,保持 Numpy 数组排序不变
【发布时间】:2020-05-11 11:16:24
【问题描述】:

(n,2) Numpy 数组的元素被打乱并在循环中产生一些噪音时,我想保留它的元素。

例如,我有一个函数将二维空间中的三个点从[[100,30],[40,80][150,20] 映射到[[39,82],[101,29],[152,21]]。我想对第二个数组进行排序,以使它们与第一个数组的欧几里得距离最小化。 (试图跟踪这个变换下的点)。

以下是此过程的示例:

a = np.random.randint(1000,size=(10,2))
for i in range(100):
    b = a + np.random.randint(low=-2, high=2,size=(10,2))
    np.random.shuffle(b)
    a = b

(如您所见,噪声幅度远小于数组值,2

我想保持数组中的初始顺序。

这是我到目前为止所做的,但失败了:

a = np.random.randint(1000,size=(10,2))
for i in range(100):
    b = a + np.random.randint(5,size=(10,2))
    np.random.shuffle(b)
    b_ = b.copy()
    for i in range(len(a)):
        dist = np.sqrt((a[i,0]-b[:,0])**2+(a[i,1]-b[:,1])**2)
        loc = np.argmin(dist)
        b_[i], b_[loc] = b_[loc], b_[i]
    b=b_.copy()
    a=b.copy()

但它以某种方式弄乱了数组元素。

【问题讨论】:

  • 如果你随机排列其中一个数组,你打算保持哪个顺序?
  • @PaddyHarrison a 的初始顺序。在我提供的示例中,第一个和第二个元素应该交换。 [[101,29],[39,82],[152,21]]

标签: python arrays numpy sorting


【解决方案1】:

我认为这可能是正确的:

from scipy.spatial.distance import cdist
import numpy as np

a = np.array([[100,30],[40,80],[150,20]])
b = np.array([[39,82],[101,29],[152,21]])

# compute Euclidean distances between all points
dists = cdist(a, b)

# dists.argmin(axis=1) gets the index of minimum distance for each input a
b[dists.argmin(axis=1)]
>>> array([[101,  29],
           [ 39,  82],
           [152,  21]])

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2022-10-23
    • 2022-01-19
    • 2018-09-26
    • 2013-05-05
    • 2011-10-03
    • 2016-01-28
    相关资源
    最近更新 更多