【问题标题】:How to solve numba lowering error with nested for loops?如何使用嵌套的 for 循环解决 numba 降低错误?
【发布时间】:2021-08-06 19:23:58
【问题描述】:

我想在数组乘积上找到函数的最小值。我从一个简单的嵌套 for 循环和比较实现开始。由于 numba 帮助我在代码的许多其他地方获得了高速加速,我发现我只需在简单的网格搜索中添加装饰器即可。一个等效的示例是以下代码:

import numpy as np
from numba import njit


@njit()
def test():

    xs = np.arange(0, 1, 0.1)
    ys = np.arange(0, 1, 0.1)

    res = [0]
    smallest_value = np.inf
    for x in xs:
        for y in ys:
            value = x*x + y*y
            if value < smallest_value:
                smallest_value = value
                res = [x, y]

    return res, smallest_value


if __name__ == "__main__":

    print(test())

当我删除装饰器时效果很好,但是使用它,我有以下错误:

File "numba_error.py", line 20:
def test():
    <source elided>

    return res, smallest_value
    ^

During: lowering "res.2 = res" at numba_error.py (20)

我遇到了以下问题:How to Solve Numba Lowering error? 但我没有可参考的模块。

【问题讨论】:

  • 无法推断res 的类型。您必须指定列表的类型。请阅读有关列表的实验性支持的 Numba 文档。在当前代码中,res 的类型发生了变异,Numba 不支持(并且可能永远不会因为编译)。
  • @JérômeRichard 看来由于res = [0] 可以推断出 res 的类型。我收到了另一条带有 res = [] 的错误消息,指出无法推断类型。

标签: python numpy optimization numba


【解决方案1】:

这个小修改对我有用:使用元组而不是列表。

import numpy as np
from numba import njit


@njit()
def test():

    xs = np.arange(0, 1, 0.1)
    ys = np.arange(0, 1, 0.1)

    res = (0,0)
    smallest_value = np.inf
    for x in xs:
        for y in ys:
            value = x*x + y*y
            if value < smallest_value:
                smallest_value = value
                res = (x,y)

    return res, smallest_value


if __name__ == "__main__":

    print(test())

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-03-12
    • 2012-10-10
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多