与numba
一起工作,我偶然发现了非常意想不到的行为。我创建了一个nb.njit
函数,我试图在其中创建int8 numpy
数组的nb.typed.List
,因此我尝试创建相应的numba
类型。
nb.int8[:] # type of the list elements
因此,我通过lsttype
关键字将此类型设置为nb.typed.List
。
l = nb.typed.List(lsttype=nb.int8[:]) # list of int8 numpy ndarrays
我得到的是:
numba.core.errors.TypingError: Failed in nopython mode pipeline (step: nopython frontend)
No implementation of function Function(<built-in function getitem>) found for signature:
>>> getitem(class(int8), slice<a:b>)
There are 16 candidate implementations:
- Of which 16 did not match due to:
Overload in function 'getitem': File: <built-in>: Line <N/A>.
With argument(s): '(class(int8), slice<a:b>)':
No match.
我想,这意味着numba
正在尝试切片nb.int8
类型对象,就好像它不理解符号一样。
因此,我尝试了另一种方式,创建了一个np.int8
类型的空数组,并使用nb.typeof
函数。
nb.typeof(np.array([], dtype=np.int8))
它返回:
numba.core.errors.TypingError: Failed in nopython mode pipeline (step: nopython frontend)
Unknown attribute 'typeof' of type Module(<module 'numba' from '/Users/.../venv37/lib/python3.7/site-packages/numba/__init__.py'>)
这个我不明白!numba
怎么能看不到自己呢?
最小示例非常简单:
import numba as nb
import numpy as np
@nb.njit
def v():
print(nb.typeof(np.array([], dtype=np.int8)))
v()
所以我尝试使用相同的功能,但没有@nb.njit
.
它打印!
array(int8, 1d, C)
另外,我尝试在函数中导入numba,因为它看不到模块,但它产生了:
numba.core.errors.UnsupportedError: Failed in nopython mode pipeline (step: analyzing bytecode)
Use of unsupported opcode (IMPORT_NAME) found
我也尝试重新安装和更新numba
和numpy
。
这是什么诡计?
我发现了一个令人讨厌的解决方法。
@nb.njit
def f(types=(nb.int8[::1], nb.float64[::1])):
a = nb.typed.List.empty_list(types[0])
b = nb.typed.List.empty_list(types[1])
# and so on...
[::1]
表示C型的一维numpy.ndarray
。
让 numba 自己弄清楚类型怎么样?
@nb.njit
def v():
l=nb.typed.List()
l.append(np.array([1,2,3], dtype=np.int8))
return l
v()
为我返回ListType[array(int8, 1d, C)]([[1 2 3]])