Home > Software design >  Nearest neighbour selection using Python
Nearest neighbour selection using Python

Time:03-03

Is there a straightforward way to select nearest neighbours based on a criterion? For instance, T1 yields array([0.04, 0.16, 0.39]). Now I wish to scan nearest neighbours of 0.04 i.e.0.55 and 0.23. It picks 0.23 since it meets the criterion (0.23<0.5). Now it scans 0.85 and 0.43 and picks 0.43<0.5 and so on...

import numpy as np

P1 = np.array([[0.04, 0.55, 0.16, 0.39, 0.51],
       [0.23, 0.85, 0.73, 0.53, 0.11],
       [0.43, 0.26, 0.1 , 0.06, 0.88],
       [0.95, 0.27, 0.61, 0.  , 0.17],
       [0.01, 0.72, 0.87, 0.14, 0.06]])

P2=0.5

T=P1[0,:]
T1=T[P2>T]
print([T1])

The desired output is

array([[0.04,0.23,0.43,0.26,0.1,0.27,0.06,0,0.17,0.14,0.06]])

CodePudding user response:

Ok, what I'm solving here is

"Given init position (i,j) in array - iteratively scan nearest neighbour (relative to a current) elements and if satisfies specific condition - repeat for a new element."

import numpy as np

def get_neighbor_indices(position, dimensions):
    '''
    dimensions is a shape of np.array
    '''
    i, j = position
    indices = [(i 1,j), (i-1,j), (i,j 1), (i,j-1)]
    return [
        (i,j) for i,j in indices
        if i>=0 and i<dimensions[0]
            and j>=0 and j<dimensions[1]
        ]

def iterate_array(init_i, init_j, arr, condition_func):
    '''
    arr is an instance of np.array
    condition_func is a function (value) => boolean
    '''
    indices_to_check = [(init_i,init_j)]
    checked_indices = set()
    result = []
    while indices_to_check:
        pos = indices_to_check.pop()
        if pos in checked_indices:
            continue
        item = arr[pos]
        checked_indices.add(pos)
        if condition_func(item):
            result.append(item)
            indices_to_check.extend(
                get_neighbor_indices(pos, arr.shape)
            )
    return result


P1 = np.array([[0.04, 0.55, 0.16, 0.39, 0.51],
       [0.23, 0.85, 0.73, 0.53, 0.11],
       [0.43, 0.26, 0.1 , 0.06, 0.88],
       [0.95, 0.27, 0.61, 0.  , 0.17],
       [0.01, 0.72, 0.87, 0.14, 0.06]])

iterate_array(0,0, P1, lambda x : x < 0.5)
  • Related