[英]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?所以,我有这段代码,我试图计算 list1 上每个元素的欧氏距离,如果 list1 有 2 个元素,它会抛出错误,对此有什么想法吗?
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.您可以直接操作
numpy
arrays 以在此处找到欧氏距离。
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.我假设
list1
或list2
包含1
元素,并且要计算另一个列表的每个元素与单个元素之间的距离。 Rest is taken care of by numpy broadcasting . Rest 由numpy 广播处理。
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
dist
:距离
array([18.69786084, 6.66483308])
where dist[0]
gives distance(list1[0], list2[0])
and dist[1]
gives distance(list1[1], list2[0])
.其中
dist[0]
给出distance(list1[0], list2[0])
并且dist[1]
给出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.即使
list1
具有任意数量的点,它也可以概括,唯一的限制是另一个列表应该只有一个点。
As you say a for loop is probably easiest here.正如您所说,for 循环在这里可能是最简单的。 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.
我没有安装 scipy 来检查。
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)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.