在用numba` @ jit(nopython = True)`装饰的函数中创建`NumPy`数组? [英] Creating `NumPy` arrays inside a function decorated with `numba`'s `@jit(nopython=True)`?

查看:1927
本文介绍了在用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"?

推荐答案

在nopython模式下不支持创建NumPy数组. Numba通过自动尝试在nopython模式下进行jit循环来缓解这种情况.这允许在函数顶部创建数组,同时仍然获得nopython模式的几乎所有性能.

NumPy array creation is not supported in nopython mode. Numba mitigates this by automatically trying to jit loops in nopython mode. This allows for array creation at the top of a function while still getting almost all the performance of nopython mode.

(我链接到一个较旧的版本,因为我认为此限制在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`数组?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆