0

Define a function that takes a 1-d NumPy array, a parameter k, and a number p. The function returns an estimate equal to the mean of the closest k points to the number p?

def k_neighbor(input_data, k, p): """Returns the k-neighbor estimate for p using data input_data.

Keyword arguments:
input_data -- NumPy array of all the data
k -- Number of k
p -- input values

Here is the function call

data = np.array([1,3,4,5,7,8,11,12,13,15,19,24,25,29,40]) print(k_neighbor(input_data=data, k=3, p=5))

dhairya
  • 375
  • 1
  • 4
  • 10

1 Answers1

1

Copying from Find nearest value in numpy array and adjusting a bit gives what you want:

import numpy as np
def find_nearest(array, value,n_neighbors=1):
    distances=np.abs(array - value)
    print(distances)

    nearest_neighbors=[]
    for i in range(0,n_neighbors):
        idx=distances.argmin()
        nearest_neighbors.append(array[idx])
        distances[idx]=np.amax(distances)

    return nearest_neighbors

data=np.array([1,3,4,5,7,8,11,12,13,15,19,24,25,29,40])
value=24
print(find_nearest(data, value,n_neighbors=3))

returns

[24, 25, 19]

Joris
  • 1,158
  • 1
  • 16
  • 25
  • in the above code if I take value=25 then it gives 25 as nearest neighbor import numpy as np def find_nearest(array, value,n_neighbors=3): distances=np.abs(array - value) nearest_neighbors=[] for i in range(0,n_neighbors): idx=distances.argmin() nearest_neighbors.append(array[idx]) distances[idx]=distances.argmax() return nearest_neighbors data=np.array([1,3,4,5,7,8,11,12,13,15,19,24,25,29,40]) value=25 print(find_nearest(data, value,n_neighbors=3)) – dhairya Jan 27 '20 at 18:55
  • import numpy as np def find_nearest(array, value,n_neighbors=3): distances=np.abs(array - value) nearest_neighbors=[] for i in range(0,n_neighbors): idx=distances.argmin() nearest_neighbors.append(array[idx]) distances[idx]=distances.argmax() return nearest_neighbors data=np.array([1,3,4,5,7,8,11,12,13,15,19,24,25,29,40]) value=25 print(find_nearest(data, value,n_neighbors=3)) value is repeated in this case – dhairya Jan 27 '20 at 19:01
  • i've changed it so it also returns the three closest numbers when the search value is already there. But i'm sure you could have done this yourselve. – Joris Jan 28 '20 at 12:06