首页 > 解决方案 > 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

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 X I 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. 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?

标签: pythonnumpynumpy-ndarray

解决方案


在 numpy 的情况下,更喜欢np.sumand np.min,而不是 Python buildinssummin.

我们可以适应npdistance2D numpy 向量:

def npdistance(x1, x2):
    return np.sum((np.array(x1)-np.array(x2))**2, axis=1)

考虑矩阵x2

x2 = np.array([[1,1,1],[2,3,4]])

矩阵x2有两个轴:

  • 第零个是向量号:x2[0]isnp.array([1, 1, 1])x2[1]is np.array([2, 3, 4]),
  • 第一个轴用于向量维度:x2[1][1]3(第一个向量的第二个元素)。

我们执行求和以获得每个向量axis=1的距离。

  • 没有np.sum axis=1它会返回标量,
  • 使用 buildinsum给出所有向量的总和 (ala axis=0)。

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]]))

给出 0。


推荐阅读