How do I find the nearest neighbour of a = (4,5,6) among the vectors
x_1 = (4,15,5)
x_2=(0.4,10,70)
x_3=(1,-3,10)
x_4=(30,80,50)
Reporting the minimum distance of a to x_1,...,x_4.
How do I find the nearest neighbour of a = (4,5,6) among the vectors
x_1 = (4,15,5)
x_2=(0.4,10,70)
x_3=(1,-3,10)
x_4=(30,80,50)
Reporting the minimum distance of a to x_1,...,x_4.
You could try something like this:
from scipy.spatial import distance
a = [4,5,6]
x1 = [4,15,5]
x2=[0.4,10,70]
x3=[1,-3,10]
x4=[30,80,50]
distances=[distance.euclidean(a, eval('x'+str(i+1))) for i in range(4)]
print("minimal distance: ", min(distances))
mini = "x"+str(distances.index(min(distances))+1)
print("nearest neighbour: "+mini+"=", eval(mini))
#Output
>>>minimal distance: 9.433981132056603
>>>nearest neighbour: x3= [1, -3, 10]
You can use numpy
:
import numpy as np
x_1 = (4, 15, 5)
x_2 = (0.4, 10, 70)
x_3 = (1, -3, 10)
x_4 = (30, 80, 50)
xs = [x_1, x_2, x_3, x_4]
a = (4, 5, 6)
ds = []
for x in xs:
p1 = np.array(x)
p2 = np.array(a)
ds.append(np.sum((p1-p2)**2)) # Distance between the 2 points
print(min(ds)) # Print smallest distance
Output:
89