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

问题描述

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

import numba

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

但是,在下面的更复杂的示例中,出现了一个我不理解的错误

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,-2,0]
    avg_val = np.array(l).mean()
    l.sort(key=lambda x: dist_from_mean(x,mu=avg_val))
    return l

它正在报告的错误如下:

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

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

解决方法

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

通过使用参数 nopython = True,您可以停用对象模式,因此 Numba 无法将所有值作为 Python 对象处理(请参阅:https://numba.pydata.org/numba-doc/latest/glossary.html#term-object-mode)。 (参考其实是我今天偶然写的另一篇文章: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

无论如何,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; 它应该可以帮助您解决类似问题!


进一步阅读和来源: