我想使用jitclass来加速我的代码。我定义了一个B类,具有2个成员变量。一个是字典,另一个是A类的对象。如何定义规范?我已经在这里停留了一段时间。谢谢。
我有这个:
TypeError:规范值应为Numba类型实例,得到
下面是代码:
class A(object):
pass
spec = [
('x', dict), # ------ how to write this line ?
('y', A), # ------ how to write this line ?
]
@jitclass(spec)
class B(object):
def __init__(self):
self.x = dict()
self.y = A()
答案 0 :(得分:0)
您不能指定jitclass
中没有显式数字类型的成员。您可以进行这项工作,但是如果A
也是jitclass
并且dict
不是标准的python字典,而是数字类型的字典(numba.typed.Dict
)。仅numba版本0.43和更高版本支持键入的dict:
import numba as nb
@nb.jitclass([('x', nb.float64)])
class A(object):
def __init__(self, x):
self.x = x
a_type = nb.deferred_type()
dict_type = nb.deferred_type()
spec = [
('x', dict_type),
('y', a_type),
]
a_type.define(A.class_type.instance_type)
dict_type.define(nb.typeof(nb.typed.Dict.empty(key_type=nb.int64, value_type=nb.float64)))
@nb.jitclass(spec)
class B(object):
def __init__(self, x, y):
self.x = x
self.y = y
a = A(3.0)
d = nb.typed.Dict.empty(key_type=nb.int64, value_type=nb.float64)
d[1] = 1.1
b = B(d, a)
print(b.y.x) # => 3.0
print(b.x[1]) # => 1.1
您是否要使用jitclass
来代替A
或使用nb.typed.Dict
来代替python dict
取决于您的特定用途-情况。