本文介绍了在用numba` @ jit(nopython = True)`装饰的函数中创建`NumPy`数组?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想在用numba@jit(nopython=True)装饰的函数内创建一个numpy数组.例如:

I would like to create a numpy array inside a function decorated with numba's @jit(nopython=True). For example:

import numpy as np
import numba

@numba.jit(nopython=True)
def funny_func():
    zero_array = np.zeros(10)

    sum_result = 0

    for elem in zero_array:
        sum_result += elem

    return sum_result

print funny_func()

编译此脚本会产生以下错误:

Compiling this script creates the following error:

UntypedAttributeError: Unknown attribute "zeros" of type Module(<module
'numpy' from 'A:\Anaconda\lib\site-packages\numpy\__init__.pyc'>)

因此,numba不支持NumPy数组创建功能.然后,如何在经过修饰的"numba函数"内部创建NumPy数组?

So, numba does't support NumPy array creation functions. How then do I create NumPy arrays inside such a decorated "numba function"?

推荐答案

文档明确地说:

(我链接到一个较旧的版本,因为我认为此限制在0.18中不存在,这意味着您使用的是较旧的版本.即使是较旧的版本,我认为在0.12左右之前也没有此限制文档,因为自动举升尚不存在,您必须手动进行,但是下面的相同方法仍然有效.)

(I linked to an older version, because I believe this limitation doesn't exist in 0.18, which implies that you're using an older one. Even older versions, I think before 0.12 or so, don't have this documentation because the auto-lifting didn't exist yet, and you had to do it manually, but the same approach below will work.)

如果您使用的Numba版本太旧而无法使用该功能,或者您所做的事情过于复杂,以致于无法使用该功能并使它无法使用,则必须手动执行相同的操作.例如:

If you're using too old a version of Numba to have that feature, or you've done something that's complicated enough to confuse that feature and make it not work, you have to do the same thing manually. For example:

@numba.jit(nopython=True)
def _funny_func(zero_array):    
    sum_result = 0

    for elem in zero_array:
        sum_result += elem

    return sum_result

@numba.jit(nopython=False)
def funny_func():
    zero_array = np.zeros(10)
    return _funny_func(zero_array)

这篇关于在用numba` @ jit(nopython = True)`装饰的函数中创建`NumPy`数组?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

10-15 07:29