数组中的Python Numba值

问题描述 投票:0回答:1

我试图检查一个数字是否在int8s的NumPy数组中。我试过这个,但它不起作用。

from numba import njit
import numpy as np

@njit
def c(b):
    return 9 in b

a = np.array((9, 10, 11), 'int8')
print(c(a))

我得到的错误是

Invalid use of Function(<built-in function contains>) with argument(s) of type(s): (array(int8, 1d, C), Literal[int](9))
 * parameterized
In definition 0:
    All templates rejected with literals.
In definition 1:
    All templates rejected without literals.
In definition 2:
    All templates rejected with literals.
In definition 3:
    All templates rejected without literals.
In definition 4:
    All templates rejected with literals.
In definition 5:
    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: typing of intrinsic-call at .\emptyList.py (6)

如何在保持性能的同时解决这个问题?将检查数组的两个值,1和-1,并且长度为32项。他们没有排序。

python arrays numpy numba
1个回答
1
投票

检查数组中是否有两个值

为了仅检查数组中是否出现两个值,我建议使用简单的强力算法。

import numba as nb
import numpy as np

@nb.njit(fastmath=True)
def isin(b):
  for i in range(b.shape[0]):
    res=False
    if (b[i]==-1):
      res=True
    if (b[i]==1):
      res=True
  return res

#Parallelized call to isin if the data is an array of shape (n,m)
@nb.njit(fastmath=True,parallel=True)
def isin_arr(b):
  res=np.empty(b.shape[0],dtype=nb.boolean)
  for i in nb.prange(b.shape[0]):
    res[i]=isin(b[i,:])

  return res

性能

#Create some data (320MB)
A=(np.random.randn(10000000,32)-0.5)*5
A=A.astype(np.int8)
res=isin_arr(A) 11ms per call

因此,通过这种方法,我获得了大约29GB / s的吞吐量,这与存储器带宽相差无几。您还可以尝试减少Testdatasize,使其适合L3缓存以避免内存带宽限制。使用3.2 MB的Testdata,我获得了100 GB / s的throuput(远超我的内存带宽),这清楚地表明这种实现是内存带宽有限的。

© www.soinside.com 2019 - 2024. All rights reserved.