如何在numba编译函数中使用np.empty;错误消息“所有模板被拒绝”

fff*_*yyy 3 python arrays numpy typing numba

当我尝试np.empty在用 numba 编译的函数定义中使用时遇到了这个奇怪的错误,并打开nopython=True以确保优化的输入有效。

这很奇怪,因为 numba 声称支持np.empty前两个参数,而我只使用前两个参数(我认为正确吗?),所以我不知道为什么它输入不正确。

@jit(nopython=True)
def empty():
    return np.empty(5, np.float)
Run Code Online (Sandbox Code Playgroud)

在 ipython notebook 中定义上述函数后,

empty()
Run Code Online (Sandbox Code Playgroud)

给出以下错误消息:

@jit(nopython=True)
def empty():
    return np.empty(5, np.float)
Run Code Online (Sandbox Code Playgroud)

MSe*_*ert 6

问题是这np.float不是numba 中 NumPy 数组的有效数据类型。您必须向 numba 提供显式 dtype。这不仅是numba 中的, , ...np.empty等其他数组创建例程的问题,也是问题。np.onesnp.zeros

要使您的示例工作,只需要进行一些更改:

from numba import jit
import numpy as np

@jit(nopython=True)
def empty():
    return np.empty(5, np.float64)  # np.float64 instead of np.float

empty()
Run Code Online (Sandbox Code Playgroud)

或者简写np.float_。或者,如果您想要 32 位浮点数,请np.float32改用。


请注意,这np.float只是普通 Python 的别名,float因此不是真正的NumPy dtype:

>>> np.float is float
True
>>> issubclass(np.float, np.generic)
False
>>> issubclass(np.float64, np.generic)
True
Run Code Online (Sandbox Code Playgroud)

同样,还有一些额外的别名只是被解释为好像它们是 NumPy dtypes ( source ):

内置 Python 类型

几种 python 类型在用于生成 dtype 对象时等效于相应的数组标量:

int          int_
bool         bool_
float        float_
complex      cfloat
bytes        bytes_
str          bytes_ (Python2) or unicode_ (Python3)
unicode      unicode_
buffer       void
(all others) object_
Run Code Online (Sandbox Code Playgroud)

但是 numba 不知道这些别名,即使不处理 numba,您也可能最好直接使用真正的dtypes

数组类型和类型之间的转换

NumPy 支持的数字类型比 Python 多得多。本节显示哪些可用,以及如何修改数组的数据类型。

Data type     Description
bool_         Boolean (True or False) stored as a byte
int_          Default integer type (same as C long; normally either int64 or int32)
intc          Identical to C int (normally int32 or int64)
intp          Integer used for indexing (same as C ssize_t; normally either int32 or int64)
int8          Byte (-128 to 127)
int16         Integer (-32768 to 32767)
int32         Integer (-2147483648 to 2147483647)
int64         Integer (-9223372036854775808 to 9223372036854775807)
uint8         Unsigned integer (0 to 255)
uint16        Unsigned integer (0 to 65535)
uint32        Unsigned integer (0 to 4294967295)
uint64        Unsigned integer (0 to 18446744073709551615)
float_        Shorthand for float64.
float16       Half precision float: sign bit, 5 bits exponent, 10 bits mantissa
float32       Single precision float: sign bit, 8 bits exponent, 23 bits mantissa
float64       Double precision float: sign bit, 11 bits exponent, 52 bits mantissa
complex_      Shorthand for complex128.
complex64     Complex number, represented by two 32-bit floats (real and imaginary components)
complex128    Complex number, represented by two 64-bit floats (real and imaginary components)
Run Code Online (Sandbox Code Playgroud)

请注意,numba支持其中一些!