简体   繁体   中英

How to broadcast this euclidean distance?

So, I have this code, I tried to calculate euclidean distance on each element on list1 it throws an error if list1 has 2 elements, any idea on this?

import numpy as np
from scipy.spatial import distance
list1 =[(10.2,20.2),(5.3,9.2)]
list2 = [(2.2,3.3)]
list1 =np.array(list1)
dist1= distance.euclidean(list1,list2)
print("distance",dist1)

prints:

ValueError: Input vector should be 1-D.

You can directly manipulate numpy arrays in order to find euclidean distances here.

I am assuming either list1 or list2 contains 1 element and distances are to be calculated between each element of the other list and the single element. Rest is taken care of by numpy broadcasting .

import numpy as np
list1 =[(10.2,20.2),(5.3,9.2)]
list2 = [(2.2,3.3)]

a = np.array(list1)
b = np.array(list2)

dist = np.sqrt(((b - a)**2).sum(axis = 1))

Output: dist

array([18.69786084,  6.66483308])

where dist[0] gives distance(list1[0], list2[0]) and dist[1] gives distance(list1[1], list2[0]) .

It generalizes even when list1 has arbitrary number of points, the only constraint is the other list should have only one point.

As you say a for loop is probably easiest here. I have changed your lists to be lists-of-lists rather than lists-of-tuples although I'm not sure that's actually necessary. I don't have scipy installed to check.

from scipy.spatial import distance
list1 =[[10.2,20.2],[5.3,9.2]]
list2 = [2.2,3.3]
for point in list1:
    dist1= distance.euclidean(point,list2)
print("distance",dist1)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM