使用numba对numpy加速遇到的坑

问题一:

numba.errors.UntypedAttributeError: Failed at nopython (nopython frontend)
Unknown attribute 'fill' of type array(float64, 2d, C)

经过查阅以下文档: numba.pydata.org/numba-doc/latest/reference/numpysupported.html

发现numba并不支持 np.fill()。因此将代码改成:

    background = np.zeros((sourceIm.shape[0], sourceIm.shape[1])) # supported
    for i, j in np.ndindex(background.shape): # np.fill not supported by numba
        background[i,j] = threshold
    background=background.astype(np.float32)

问题二:

numba.errors.TypingError: Failed at nopython (nopython frontend)

Internal error at <numba.typeinfer.CallConstraint object at 0x7f726d5ba8>:

numba.errors.InternalError: 'Integer' object has no attribute 'ndim'

[1] During: resolving callee type: Function(<function where at 0x7f86f67bf8>)

[2] During: typing of call at test_depth_im.py (24)

查看错误出现位置,发现在np.where(),但查询上述文档,发现numba是支持np.where()的。于是怀疑是数据类型未指明导致nopython模式无法启动。

在np.where()之前添加如下两行代码,以检查numba推断出的类型:

@njit(float32[:,:,:](float32[:,:,:], float32),parallel=True, fastmath=True) 
def depthFilter(depthInfo, threshold):
    #print(numba.typeof(depthInfo))
    #print(numba.typeof(threshold))

不料竟然又报错:

numba.errors.TypingError: Failed at nopython (nopython frontend)
Untyped global name 'numba': cannot determine Numba type of <class 'object'>

numba.errors.UntypedAttributeError: Failed at nopython (nopython frontend)
Unknown attribute 'typeof' of type Module(<module 'numba' from '/usr/lib/python3/dist-packages/numba/__init__.py'>)

解决方法: 将函数上方的njit装饰器注释掉即可 ()

数据类型为:

array(int32, 3d, C)
float64

于是考虑将数据类型转化一致

1. 数组需要用np.astype()转换: x=x.astype(np.float32)

2. 标量通过加点: 7300 -> 7300. 并在装饰器中指明signature为 float32

否则可能遇到如下错误:

Traceback (most recent call last):
File "test_depth_im.py", line 47, in <module>
depthFilter(float(x),7300.)
TypeError: only size-1 arrays can be converted to Python scalars

或者:

numba.errors.TypingError: Failed at nopython (nopython frontend)
Invalid usage of type(CPUDispatcher(<function SQDIFF at 0x7f8afcc840>)) with parameters (array(float64, 2d, C), array(float32, 2d, A))
Known signatures:
* (array(float32, 2d, A), array(float32, 2d, A)) -> float32
* parameterized

总之,使用装饰器的signature功能显示指出形参和返回值类型,并在函数调用前做好类型转换,确保形参类型一致。

回到一开始的np.where()报错问题,幸好看到了这个链接:github.com/numba/numba/issues/3650

depthInfo = np.where(depthInfo<threshold, depthInfo, threshold)

在普通的python代码中,如果threshold是标量,depthInfo无论是几维的数组,代码都是没有问题的。但是如果使用如上的numba装饰器对代码加速,则出现问题二一开始的错误。根据issue中的解决方法,我们需要构造一个维度和尺寸一样的数组,并将其填满需要替换的值:

background = np.zeros((depthInfo.shape[0], depthInfo.shape[1], depthInfo.shape[2])) # supported
    for i,j,k in np.ndindex(background.shape):
        background[i,j,k]=threshold
    background=background.astype(np.float32)
    depthInfo = np.where(depthInfo<threshold, depthInfo, background) # supported

numba不再报错了。

问题三:

numba.errors.InternalError: tuple index out of range

[1] During: typing of static-get-item at test_depth_im.py (28)

同样出现在以上代码中(修改前),这主要是维度一致的问题,如果depthInfo和background维度不一样就会报这个错误;此外,装饰器signature中的数组维度应与实际数据一致。

总结:

1.  numba 的nopython模式对数据类型的一致性要求很高,在使用较复杂的数据(多维矩阵、浮点数(小数))进行运算时,最好提前做好类型转换和声明的工作,以免产生谷歌都搜不到的错误。

2. numba支持的numpy类型和函数等可以查阅官方文档:numba.pydata.org/numba-doc/latest/reference/numpysupported.html

3.使用以上numba装饰器对numpy加速的结果:

序号 numba编译时间(s) numba加速执行时间(s) 无numba加速执行时间(s)
1 1.359856367111206 0.05226278305053711 3.891127586364746
2 1.3733365535736084 0.052794694900512695 2.9139089584350586
3 1.3658461570739746 0.052443504333496094 2.358830451965332

threshold

原文地址:https://www.cnblogs.com/mrlonely2018/p/14744699.html