[英]How do I iterate over an ndarray without using for/while loops?
For two given 1-d arrays or lists I can calculate the squared Euclidean distance via the function对于两个给定的一维 arrays 或列表,我可以通过 function 计算平方欧几里得距离
import numpy as np
def npdistance(x1, x2):
return sum((np.array(x1)-np.array(x2))**2)
Now for a given vector v and 2d-array XI would like to find the shortest squared Euclidean distance of any vector contained in X to the vector u without iterating over the elements of X with for/while loops.现在对于给定的向量 v 和 2d 数组 XI 想要找到包含在 X 中的任何向量到向量 u 的最短平方欧几里得距离,而不用 for/while 循环迭代 X 的元素。 My attempt is
我的尝试是
def npnearest(u, X):
L=npdistance(u,X)
return min(L)
which does not give me what I want.这并没有给我想要的东西。 For example
例如
npnearest(np.array([1,1,1]), np.array([[1,1,1],[2,3,4]]))
would give me 16 instead of 0. How can I do it?会给我 16 而不是 0。我该怎么做?
In case of numpy, prefer np.sum
and np.min
, rather than Python buildins sum
and min
.在 numpy 的情况下,更喜欢
np.sum
和np.min
,而不是 Python 内置sum
和min
。
We can adapt npdistance
for 2D numpy vectors:我们可以为二维 numpy 向量调整
npdistance
:
def npdistance(x1, x2):
return np.sum((np.array(x1)-np.array(x2))**2, axis=1)
Consider matrix x2
:考虑矩阵
x2
:
x2 = np.array([[1,1,1],[2,3,4]])
Matrix x2
has two axes:矩阵
x2
有两个轴:
x2[0]
is np.array([1, 1, 1])
and x2[1]
is np.array([2, 3, 4])
,x2[0]
是np.array([1, 1, 1])
和x2[1]
是np.array([2, 3, 4])
,x2[1][1]
is 3
(second element of first vector).x2[1][1]
为3
(第一个向量的第二个元素)。 We perform sum along axis=1
to get distances for each vector.我们沿
axis=1
执行求和以获得每个向量的距离。
np.sum
axis=1
it would return scalar,np.sum
axis=1
它会返回标量,sum
gives sum of all vectors (ala axis=0
).sum
给出所有向量的总和(ala axis=0
)。 npnearest
works correct in this case.在这种情况下,
npnearest
工作正常。
def npnearest(u, X):
L=npdistance(u,X)
return min(L)
npnearest(np.array([1,1,1]), np.array([[1,1,1],[2,3,4]]))
gives 0.给出 0。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.