如何在 python 中使用 numba.jit 将计算值传递到列表排序?

tib*_*ius 5 python jit numba

我正在尝试使用 Python 中的 numba-jit 函数中的自定义键对列表进行排序。简单的自定义键可以工作,例如我知道我可以使用如下所示的绝对值进行排序:

import numba

@numba.jit(nopython=True)
def myfunc():
    mylist = [-4, 6, 2, 0, -1]
    mylist.sort(key=lambda x: abs(x))
    return mylist  # [0, -1, 2, -4, 6]
Run Code Online (Sandbox Code Playgroud)

但是,在下面更复杂的示例中,我收到一个我不理解的错误。

import numba
import numpy as np


@numba.jit(nopython=True)
def dist_from_mean(val, mu):
    return abs(val - mu)

@numba.jit(nopython=True)
def func():
    l = [1,7,3,9,10,-4,-2,0]
    avg_val = np.array(l).mean()
    l.sort(key=lambda x: dist_from_mean(x, mu=avg_val))
    return l
Run Code Online (Sandbox Code Playgroud)

它报告的错误如下:

Traceback (most recent call last):
  File "testitout.py", line 18, in <module>
    ret = func()
  File "/.../python3.6/site-packages/numba/core/dispatcher.py", line 415, in _compile_for_args
    error_rewrite(e, 'typing')
  File "/.../python3.6/site-packages/numba/core/dispatcher.py", line 358, in error_rewrite
    reraise(type(e), e, None)
  File "/.../python3.6/site-packages/numba/core/utils.py", line 80, in reraise
    raise value.with_traceback(tb)
numba.core.errors.TypingError: Failed in nopython mode pipeline (step: convert make_function into JIT functions)
Cannot capture the non-constant value associated with variable 'avg_val' in a function that will escape.

File "testitout.py", line 14:
def func():
    <source elided>
    l.sort(key=lambda x: dist_from_mean(x, mu=avg_val))
                                                ^
Run Code Online (Sandbox Code Playgroud)

你知道这里发生了什么吗?

J. *_*old 2

你知道这里发生了什么吗?

通过使用该参数,nopython = True您可以停用对象模式,因此 Numba 无法将所有值作为 Python 对象处理(请参阅: https: //numba.pydata.org/numba-doc/latest/glossary.html#term-object -模式)。(参考其实是我今天偶然写的另一篇文章:How call a `@guvectorize` inside a `@guvectorize` in numba?

@numba.jit(nopython=True)
def func():
    l = [1,7,3,9,10,-4,-2,0]
    avg_val = np.array(l).mean()
    l.sort(key=lambda x: dist_from_mean(x, mu=avg_val))
    return l
Run Code Online (Sandbox Code Playgroud)

无论如何,lambda对于 numba jit 函数来说“太”复杂了——至少当它作为参数传递时(比较https://github.com/numba/numba/issues/4481)。激活模式后,nopython您只能使用有限数量的库 - 完整列表可以在此处找到: https: //numba.pydata.org/numba-doc/dev/reference/numpysupported.html

这就是为什么它会抛出以下错误:

numba.core.errors.TypingError:在 nopython 模式管道中失败(步骤:将 make_function 转换为 JIT 函数)无法捕获与将转义的函数中的变量“avg_val”关联的非常量值。

此外,当您在另一个函数中引用 jit 加速函数时 - 当具有nopython = True. 这也可能是问题的根源。

我强烈建议您查看以下教程:http://numba.pydata.org/numba-doc/latest/user/5minguide.html#will-numba-work-for-my-code;它应该可以帮助您解决类似的问题!


进一步阅读和来源: