【问题标题】:How to iterate two arrays in numpy/numba (zip throws error)如何在 numpy/numba 中迭代两个数组(zip 抛出错误)
【发布时间】:2020-07-30 13:20:24
【问题描述】:

我有以下代码用于计算给定距离矩阵的路径的距离。

dist_matrix = np.array(
    [
        [0.0, 0.5, 1.0, 1.41421356, 1.0],
        [0.5, 0.0, 0.5, 1.11803399, 1.11803399],
        [1.0, 0.5, 0.0, 1.0, 1.41421356],
        [1.41421356, 1.11803399, 1.0, 0.0, 1.0],
        [1.0, 1.11803399, 1.41421356, 1.0, 0.0],
    ]
)

@jit(nopython=True)
def calc_dist(tour):
    return np.sum(np.array([dist_matrix[i, j] for i, j in zip([tour[0:-1]], tour[1:])]))

tour = [0, 1, 2, 3, 4]
print(calc_dist(tour))

预期输出:2.118

但它抛出以下错误:

numba.errors.TypingError: Failed in nopython mode pipeline (step: nopython frontend)
Invalid use of Function(<intrinsic range_iter_len>) with argument(s) of type(s): (zip(iter(list(reflected list(int64))), iter(reflected list(int64))))```

我知道我可以通过设置nopython=False 来消除错误,但我的理解是它并不值得使用 numba,除非你可以将它与nopython=True 一起使用。但是我无法弄清楚如何在我的calc_distance 函数中替换zip。用 numpy/numba 替换 zip 的最佳方法是什么?

【问题讨论】:

  • 我认为这里有一个错字:zip([tour[0:-1]], tour[1:]) 一个有括号,一个没有。不确定它是否相关。也可能值得一试:np.vstack((np.array(tour[0:-1]), np.array(tour[1:])))。似乎在我的系统上工作,但我不是 numba 专家。

标签: python numpy iterator numba


【解决方案1】:

如果你有 numpy 数组,你可以使用 dstack():

import numpy as np

a = np.array([1,2,3,4,5])
b = np.array([6,7,8,9,10])

c = np.dstack((a,b))
#or
d = np.column_stack((a,b))

>>> c
array([[[ 1,  6],
        [ 2,  7],
        [ 3,  8],
        [ 4,  9],
        [ 5, 10]]])
>>> d
array([[ 1,  6],
       [ 2,  7],
       [ 3,  8],
       [ 4,  9],
       [ 5, 10]])

>>> c.shape
(1, 5, 2)
>>> d.shape
(5, 2)

【讨论】:

  • 感谢拉胡尔的回答。您能否详细说明您的答案,以显示您将如何使用它来计算[dist_matrix[i, j] for i, j in zip([tour[0:-1]], tour[1:])],就像我的问题一样?我已经用预期的结果更新了问题
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2013-05-14
  • 1970-01-01
  • 1970-01-01
  • 2019-04-09
  • 2014-06-30
  • 2018-11-03
  • 2012-09-28
相关资源
最近更新 更多