为什么 numpy.array 在 jitclass numba 中给出错误?

Why numpy.array gives an error in jitclass numba?

我试图在 jitclass 中用 np.array 初始化一个矩阵,但它只是给我一个错误

例如:

from numba.experimental import jitclass
from numba import int32, float64
import numpy as np

spec = [('n',float64[:,:])]

@jitclass(spec)
class myclass(object):

  def __init__(self ):
    self.n = np.array([[0.,1],[2,3],[4,5]])

if __name__ == '__main__':
    pop = myclass()

给我:

Traceback (most recent call last):
  File "C:/Users/maxime/Desktop/SESAME/PycharmProjects/LargeScale_2021_04_23/di.py", line 14, in <module>
    pop = myclass()
  File "C:\Python389\lib\site-packages\numba\experimental\jitclass\base.py", line 124, in __call__
    return cls._ctor(*bind.args[1:], **bind.kwargs)
  File "C:\Python389\lib\site-packages\numba\core\dispatcher.py", line 482, in _compile_for_args
    error_rewrite(e, 'typing')
  File "C:\Python389\lib\site-packages\numba\core\dispatcher.py", line 423, in error_rewrite
    raise e.with_traceback(None)
numba.core.errors.TypingError: Failed in nopython mode pipeline (step: nopython frontend)
Internal error at <numba.core.typeinfer.CallConstraint object at 0x000002A07F85BF40>.
Failed in nopython mode pipeline (step: native lowering)

Enable logging at debug level for details.

File "<string>", line 3:
<source missing, REPL/exec in use?>

我不明白为什么我不能启动我的矩阵。

我找到了这个解决方法:

from numba.experimental import jitclass
from numba import int32, float64
import numpy as np

spec = [('n',float64[:,:])]

@jitclass(spec)
class myclass(object):

  def __init__(self ):
    # self.n = np.array([[0.,1],[2,3],[4,5]])
    self.n = np.vstack((np.array([0., 1]), np.array([2., 3]), np.array([4., 5])))

if __name__ == '__main__':
    pop = myclass()
    print(pop.n)    

但我更愿意直接使用数组函数

您应该在每个列表中至少声明一个浮点数,就像您在解决方法中所做的那样,以便 Numba 可以推断出数组的唯一类型:

self.n = np.array([[0.,1],[2.,3],[4.,5]])

声明类型也有帮助:

self.n = np.array([[0,1],[2,3],[4,5]], dtype=nb.float64)