简体   繁体   English

如何在不使用 for/while 循环的情况下迭代 ndarray?

[英]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.sumnp.min ,而不是 Python 内置summin

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有两个轴:

  • zeroth is vector number: 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])
  • first axis is for vector dimension: 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执行求和以获得每个向量的距离。

  • Without np.sum axis=1 it would return scalar,如果没有np.sum axis=1它会返回标量,
  • Using buildin 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.

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