1

거리의 2D 배열이 주어지면 argsort를 사용하여 인덱스 배열을 생성합니다. 여기서 첫 번째 요소는 행의 가장 낮은 값의 인덱스입니다. 인덱싱을 사용하여 첫 번째 K 열만 선택하십시오. 예를 들어 K = 3입니다. 그때 수행 싶은 것이로우 당 N 값이 가장 낮은 위치의 마스크 배열 생성

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의 최단 거리를 산출 만 인덱스를 반환 마스크 배열을 생성한다.

1 차원 배열에서 작동하는 일부 코드에서이 접근 방식을 사용했습니다.

# 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() 
+0

은 무엇입니까 그 2D 케이스의 예상 출력은? – Divakar

+0

주로 True 요소를 가진 마스크 ​​배열이 될 것이고, 가장 낮은 K 값만 각 행에서 False가됩니다. –

답변

1

여기 하나의 방법 -

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와 처음 사용하는 경우 큰 단계가 될 수 advanced-indexing을 포함하지만, 기본적으로 여기에 우리가 컬럼에 인덱스 k_idx를 사용하여 우리는 np.arange(k_idx.shape[0])[:,None]의 범위 배열을 사용하여 행에 색인을 생성하는 인덱스의 튜플을 형성합니다. advanced-indexing에 대한 자세한 정보 우리는과 같이, np.argpartition를 사용하는 대신 argsort하여 성능을 향상시킬 수

-

k_idx = np.argpartition(position, N)[:,:N] 

샘플 입력, 경우에 대한 출력은 거짓으로 행 당 가장 낮은 3 요소를 설정 -

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) 
+0

감사합니다. 나는 어떻게되는지는 모르지만 그것은 그렇다. –

+0

@ user2038074 도움이 될만한 의견이 추가되었습니다. – Divakar