0

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.

i9-9980XE
  • 11
  • 5
  • 2
    Calculate the distances and select the smallest one? What have you tried? Where are you stuck? Also, if this is e.g. in the context of `numpy`, please tag it as such. Python per se doesn't have any notion of `vector` or `matrix`. – John Coleman Jun 11 '20 at 23:28
  • Do I just do a=[4,5,6] x1=[4,15,5] then d=numpy.linalg.norm(a-x1) – i9-9980XE Jun 11 '20 at 23:29
  • 1
    See [this question](https://stackoverflow.com/q/1401712/4996248) about ways to calculate distance in Python (including the `linalg.norm` that you mention). – John Coleman Jun 11 '20 at 23:33

2 Answers2

0

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]
MrNobody33
  • 6,413
  • 7
  • 19
0

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
Oddthinking
  • 24,359
  • 19
  • 83
  • 121
Red
  • 26,798
  • 7
  • 36
  • 58