为什么numpy.array在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:Python389libsite-packagesnumbaexperimentaljitclassbase.py", line 124, in __call__
return cls._ctor(*bind.args[1:], **bind.kwargs)
File "C:Python389libsite-packagesnumbacoredispatcher.py", line 482, in _compile_for_args
error_rewrite(e, 'typing')
File "C:Python389libsite-packagesnumbacoredispatcher.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)    

但我更喜欢直接使用数组函数。

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

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

声明类型也有帮助:

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

最新更新