Python 生成每行重置最低N值位置的掩码数组

Python 生成每行重置最低N值位置的掩码数组,python,numpy,multidimensional-array,nearest-neighbor,masked-array,Python,Numpy,Multidimensional Array,Nearest Neighbor,Masked Array,给定一个2D距离数组,使用argsort生成一个索引数组,其中第一个元素是行中最低值的索引。使用索引仅选择前K列,例如K=3 position = np.random.randint(100, size=(5, 5)) array([[36, 63, 3, 78, 98], [75, 86, 63, 61, 79], [21, 12, 72, 27, 23], [38, 16, 17, 88, 29], [93, 37, 48, 88, 10]]) idx = posi

给定一个2D距离数组,使用argsort生成一个索引数组,其中第一个元素是行中最低值的索引。使用索引仅选择前K列,例如K=3

position = np.random.randint(100, size=(5, 5))
array([[36, 63,  3, 78, 98],
   [75, 86, 63, 61, 79],
   [21, 12, 72, 27, 23],
   [38, 16, 17, 88, 29],
   [93, 37, 48, 88, 10]])
idx = position.argsort()
array([[2, 0, 1, 3, 4],
   [3, 2, 0, 4, 1],
   [1, 0, 4, 3, 2],
   [1, 2, 4, 0, 3],
   [4, 1, 2, 3, 0]])
idx[:,0:3]
array([[2, 0, 1],
   [3, 2, 0],
   [1, 0, 4],
   [1, 2, 4],
   [4, 1, 2]])
然后我想做的是创建一个屏蔽数组,当应用到原始位置数组时,它只返回产生k个最短距离的索引

我将这种方法基于我发现的一些代码,这些代码可以在一维数组上工作

# https://glowingpython.blogspot.co.uk/2012/04/k-nearest-neighbor-search.html

from numpy import random, argsort, sqrt
from matplotlib import pyplot as plt    

def knn_search(x, D, K):
    """ find K nearest neighbours of data among D """
    ndata = D.shape[1]
    K = K if K < ndata else ndata
    # euclidean distances from the other points
    sqd = sqrt(((D - x[:, :ndata]) ** 2).sum(axis=0))
    idx = argsort(sqd)  # sorting
    # return the indexes of K nearest neighbours
    return idx[:K]

# knn_search test
data = random.rand(2, 5)  # random dataset
x = random.rand(2, 1)  # query point

# performing the search
neig_idx = knn_search(x, data, 2)

figure = plt.figure()
plt.scatter(data[0,:], data[1,:])
plt.scatter(x[0], x[1], c='g')
plt.scatter(data[0, neig_idx], data[1, neig_idx], c='r', marker = 'o')
plt.show()
这里有一条路-

N = 3 # number of points to be set as False per row

# Slice out the first N cols per row
k_idx = idx[:,:N]

# Initialize output array
out = np.ones(position.shape, dtype=bool)

# Index into output with k_idx as col indices to reset
out[np.arange(k_idx.shape[0])[:,None], k_idx] = 0
最后一步涉及高级索引,如果您是NumPy新手,这可能是一个很大的步骤,但基本上这里我们使用k_idx索引到列中,我们正在形成索引元组,以索引到行,范围数组为np.arangek_idx.shape[0][:,None]。更多信息

我们可以通过使用而不是argsort来提高性能,如下所示-

k_idx = np.argpartition(position, N)[:,:N]
示例输入,案例输出,将每行最低3个元素设置为False-

In [227]: position
Out[227]: 
array([[36, 63,  3, 78, 98],
       [75, 86, 63, 61, 79],
       [21, 12, 72, 27, 23],
       [38, 16, 17, 88, 29],
       [93, 37, 48, 88, 10]])

In [228]: out
Out[228]: 
array([[False, False, False,  True,  True],
       [False,  True, False, False,  True],
       [False, False,  True,  True, False],
       [ True, False, False,  True, False],
       [ True, False, False,  True, False]], dtype=bool)

2D情况下的预期输出是什么?它将是一个以真元素为主的掩码数组,每行中只有K个最低值为假。谢谢,这是可行的。我不知道怎么做,但确实如此。@user2038074添加了更多的注释以帮助解决问题。