【问题标题】:Why is Numba failing to compile this function?为什么 Numba 无法编译此函数?
【发布时间】:2020-07-11 06:56:25
【问题描述】:

我正在尝试使用 Numba 编译以下函数:

@njit(fastmath=True, nogil=True)
def generate_items(array, start):
    array_positions = np.empty(SIZE, dtype=np.int64)
    count = 0
    while count < SIZE - start:
        new_array = mutate(np.empty(0, dtype=np.uint8))

        if len(new_array) > 0:
            array_positions[count] = len(array)  # <<=== FAILS HERE
            array = np.append(array, np.append(new_array, 255))
            count += 1

    return array, array_positions

但它在上面指示的行上失败并显示以下错误消息:

numba.core.errors.TypingError: Failed in nopython mode pipeline (step: nopython frontend)
Cannot unify array(uint8, 1d, C) and array(int64, 1d, C) for 'array.3', defined at ...

这似乎没有意义,因为我只是将 intlen 上的结果)分配给具有 dtypenp.int64 的数组?

请注意,array 的类型为 np.uint8 - 但我没有分配数组本身,所以这条消息对我来说毫无意义。

我尝试对此进行重构:

tmp = len(array)  # <<=== FAILS HERE
array_positions[count] = tmp  

但是它在那里失败了......同样的消息。

我还尝试用array.size 替换len(array),因为这是一个一维数组,但同样的错误。

谁能明白为什么会失败?

我使用的是 Python 3.7 和 Numba 0.50

谢谢!

【问题讨论】:

  • 不,这是一个不同的问题。我没有在这种情况下使用连接。
  • np.append 使用np.concatenate。我不确定numba,但在循环中使用np.append(或任何连接/堆栈系列)是一个坏主意——速度慢,而且通常很难正确处理。我们建议将数组收集在一个列表中,并在最后进行 一个 连接。
  • 花几分钟看看np.append的python代码。你会看到,即使在numpy 中,它也不是一个很好的功能。另一件事,当在numba 中使用concatenate 时,给它一个元组参数,而不是一个列表。

标签: python python-3.x numpy numba


【解决方案1】:

第一个问题是您使用了不受支持的函数mutate (as stated here)。 接下来,正如错误所说,您尝试在

中添加具有不同数据类型的数组
np.append(array, np.append(new_array, 255))

其中arrayint64 类型,new_array 保存uint8 类型的值。如果您使用了@jit,它会向您显示下降到object 模式的警告,但是因为您已经使用@njit 装饰器强制执行nonpython 模式,它会引发错误。 干杯。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2021-09-26
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2023-03-11
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多