Numba:根据转换规则“安全”,无法将输入强制为任何支持的类型

Cra*_*cin 5 python numba

我最近一直在与 numba 作斗争。直接从 numba 文档复制此代码片段,它工作正常:

@guvectorize([(int64[:], int64, int64[:])], '(n),()->(n)')
def g(x, y, res):
    for i in range(x.shape[0]):
        res[i] = x[i] + y

a = np.arange(5)
g(a,2)
Run Code Online (Sandbox Code Playgroud)

给 y 一个数组会产生一个网格。对 2 个数组求和是我经常做的事情,所以这是我通过修改代码片段得出的代码。

@guvectorize([(int64[:], int64[:], int64[:])], '(n),(n)->(n)')
def add_arr(x, y, res):
    for i in range(x.shape[0]):
        res[i] = x[i] + y[i]

p = np.ones(1000000)
q = np.ones(1000000)
r = np.zeros(1000000)

add_arr(p,q)
Run Code Online (Sandbox Code Playgroud)

这给了我错误:

TypeError                                 Traceback (most recent call last)
<ipython-input-75-074c0fd345aa> in <module>()
----> 1 add_arr(p,q)

TypeError: ufunc 'add_arr' not supported for the input types, and the      inputs could not be safely coerced to any supported types according to the casting rule ''safe''
Run Code Online (Sandbox Code Playgroud)

我之前曾多次遇到此错误,但我不知道它意味着什么或如何修复它。我怎样才能得到想要的结果?提前致谢。

小智 5

您正在使用numpy.ones生成列表,并根据文档(https://docs.scipy.org/doc/numpy/reference/ generated/numpy.ones.html):

dtype :数据类型,可选

数组所需的数据类型,例如 numpy.int8。默认为 numpy.float64。

np.ones(1000000)是一个列表numpy.float64。但你的add_arr规范需要 的列表int64,因此TypeError爆炸了。

一个简单的修复:

p = np.ones(1000000, dtype=np.int64)
q = np.ones(1000000, dtype=np.int64)
Run Code Online (Sandbox Code Playgroud)