+-
python – numba中的int数组
我正在计算int8s向量中最常用的数字.当我建立一个反向数组时,Numba抱怨:

@jit(nopython=True)
def freq_int8(y):
    """Find most frequent number in array"""
    count = np.zeros(256, dtype=int)
    for val in y:
        count[val] += 1
    return ((np.argmax(count)+128) % 256) - 128

调用它我收到以下错误:

TypingError: Invalid usage of Function(<built-in function zeros>) with parameters (int64, Function(<class 'int'>))

如果我删除dtype = int它可以工作,我获得了不错的加速.然而,我很困惑为什么宣布一系列的int不起作用.有没有已知的解决方法,这里有没有值得拥有的效率增益?

背景:我试图削减一些重量级代码的微秒.我特别受到numpy.median的伤害,并一直在调查Numba,但我正努力改善中位数.找到最频繁的数字是中位数的可接受的替代方案,在这里我已经能够获得一些性能.上面的numba代码也比numpy.bincount快.

更新:输入接受的答案后,这里是int8向量的中位数实现.它比numpy.median快大约一个数量级:

@jit(nopython=True)
def median_int8(y):
    N2 = len(y)//2
    count = np.zeros(256, dtype=np.int32)
    for val in y:
        count[val] += 1
    cs = 0
    for i in range(-128, 128):
        cs += count[i]
        if cs > N2:
            return float(i)
        elif cs == N2:
            j = i+1
            while count[j] == 0:
                j += 1
            return (i + j)/2

令人惊讶的是,短向量的性能差异更大,显然是由于numpy向量的开销:

>>> a = np.random.randint(-128, 128, 10)

>>> %timeit np.median(a)
    The slowest run took 7.03 times longer than the fastest. This could mean that an intermediate result is being cached.
    10000 loops, best of 3: 20.8 µs per loop

>>> %timeit median_int8(a)
    The slowest run took 11.67 times longer than the fastest. This could mean that an intermediate result is being cached.
    1000000 loops, best of 3: 593 ns per loop

这个开销是如此之大,我想知道是否有问题.

最佳答案
简单来说,找到最频繁的数字通常称为 mode,它与中位数相似,因为它是平均值…在这种情况下,np.mean会相当快.除非您的数据存在某些约束或特殊情况,否则 there is no guarantee that the mode approximates the median.

如果您仍然想要计算整数列表的模式,正如您所提到的,np.bincount应该足够了(如果numba更快,它应该不会太多):

count = np.bincount(y, minlength=256)
result = ((np.argmax(count)+128) % 256) - 128

注意我已将minlength参数添加到np.bincount,因此它返回与代码中相同的256长度列表.但是在实践中完全没有必要,因为你只想要argmax,np.bincount(没有minlength)将返回一个列表,其长度是y中的最大数.

至于numba错误,用dtype = np.int32替换dtype = int应该可以解决问题. int是一个python函数,你在numba头中指定了nopython.如果你删除了nopython,那么dtype = int或dtype =’i’也会起作用(具有相同的效果).

点击查看更多相关文章

转载注明原文:python – numba中的int数组 - 乐贴网