我在使用@jit(nopython=True)
解决(可能是基本的)Numba错误时遇到麻烦。归结为下面的最小示例,它产生一个TypingError
(下面是完整的日志)。如果相关,我正在使用Python 3.6.10和Numba v0.49.0。
错误发生在创建numpy数组的d
行上(如果我删除d
并返回c
,它会正常工作)。我该如何解决?
from numba import jit
import numpy as np
n = 5
foo = np.random.rand(n,n)
@jit(nopython=True)
def bar(x):
a = np.array([0,3,2])
b = np.array([1,2,3])
c = [x[i,j] for i,j in zip(a,b)]
# print(c) # Un-commenting this line solves the issue‽ (per @Ethan's comment)
d = np.array(c)
return d
baz = bar(foo)
出现完整错误:
---------------------------------------------------------------------------
TypingError Traceback (most recent call last)
<ipython-input-13-950d2be33d72> in <module>
14 return d
15
---> 16 baz = bar(foo)
17 print(baz)
~/miniconda3/envs/py3k/lib/python3.6/site-packages/numba/core/dispatcher.py in _compile_for_args(self, *args, **kws)
399 e.patch_message(msg)
400
--> 401 error_rewrite(e, 'typing')
402 except errors.UnsupportedError as e:
403 # Something unsupported is present in the user code, add help info
~/miniconda3/envs/py3k/lib/python3.6/site-packages/numba/core/dispatcher.py in error_rewrite(e, issue_type)
342 raise e
343 else:
--> 344 reraise(type(e), e, None)
345
346 argtypes = []
~/miniconda3/envs/py3k/lib/python3.6/site-packages/numba/core/utils.py in reraise(tp, value, tb)
77 value = tp()
78 if value.__traceback__ is not tb:
---> 79 raise value.with_traceback(tb)
80 raise value
81
TypingError: Failed in nopython mode pipeline (step: nopython frontend)
Invalid use of Function(<intrinsic range_iter_len>) with argument(s) of type(s): (zip(iter(array(int64, 1d, C)), iter(array(int64, 1d, C))))
* parameterized
In definition 0:
All templates rejected with literals.
In definition 1:
All templates rejected without literals.
This error is usually caused by passing an argument of a type that is unsupported by the named function.
[1] During: resolving callee type: Function(<intrinsic range_iter_len>)
[2] During: typing of call at <ipython-input-13-950d2be33d72> (9)
File "<ipython-input-13-950d2be33d72>", line 9:
def bar(x):
a = np.array([0,3,2])
^
更新:使用以下功能以类似的方式失败(尽管在这种情况下print(c)
技巧没有帮助):
@jit(nopython=True)
def bar(x):
a = [0,3,2]
b = [1,2,3]
c = x[a, b]
d = np.array(c)
return d
该函数的第一个版本存在问题,并且添加print(c)
可以解决该问题,这对我来说还是个谜。 Numba应该实现zip
(显然,在这种确切情况下,它可以通过print(c)
行触发),因此,这似乎是一个错误。
该函数的第二个版本的问题少了一个谜。根据current Numba documentation:
数组支持常规迭代。支持完整的基本索引和切片。还支持高级索引的一个子集:只允许一个高级索引,并且它必须是一维数组(也可以与任意数量的基本索引组合)。
由于您正在尝试在
a
行中使用两个高级索引b
和c = x[a, b]
,因此Numba不支持该代码。确实,这就是冗长的错误消息Invalid use of Function(<built-in function getitem>) with argument(s) of type(s): (array(float64, 2d, C), tuple(array(int64, 1d, C) x 2))
所说的。
如果我们改为编写c=x[a,2]
,则该代码将起作用,这与Numba允诺允许一个高级索引一致。
[通常,我发现使用Numba的最安全方法是编写循环样式而没有NumPy的更高级功能。这有点不幸,因为这几乎就像我们需要用C的方言来编写,而不是Python一样,但是从正面看,它仍然比实际编写C更加方便。
就此而言,以下代码很好用:
@jit(nopython=True)
def bar(x):
a = np.array([0,3,2])
b = np.array([1,2,3])
c = np.empty(len(a))
for i in range(len(a)):
c[i] = x[a[i], b[i]]
return c