python - 如何将 numpy.double、numpy.single 和 struct.Struct 类型的类属性转换为各自的 numba 类型?
问题描述
如何将 numpy.double、numpy.single 和 struct.Struct 类型的类属性转换为各自的 numba 类型,以便能够在 jitclass 中使用这些属性?
1)例如,类属性之一具有以下形式:
self.type = numpy.double
为了编译具有此类属性的 python 类,我必须将其映射到 numba 类型。我试过 numba.typeof(numpy.double) 但它会产生以下错误
In [1]: a=numpy.double
In [2]: numba.typeof(a)
---------------------------------------------------------------------------
ValueError Traceback (most recent call last)
<ipython-input-244-7ab9d6ba8d0a> in <module>
----> 1 numba.typeof(a)
C:\ProgramData\Anaconda3\lib\site-packages\numba\typing\typeof.py in typeof(val
purpose)
32 msg = _termcolor.errmsg(
33 "cannot determine Numba type of %r") % (type(val),)
---> 34 raise ValueError(msg)
35 return ty
36
ValueError: cannot determine Numba type of <class 'type'>
2)在使用 struct.Struct 的情况下,我得到了类似的错误
In [1]: from struct import Struct
In [2]: a = Struct(">dd")
In [3]: numba.typeof(a)
---------------------------------------------------------------------------
ValueError Traceback (most recent call last)
<ipython-input-76-7ab9d6ba8d0a> in <module>
----> 1 numba.typeof(a)
C:\ProgramData\Anaconda3\lib\site-packages\numba\typing\typeof.py in typeof(val,
purpose)
32 msg = _termcolor.errmsg(
33 "cannot determine Numba type of %r") % (type(val),)
---> 34 raise ValueError(msg)
35 return ty
36
ValueError: cannot determine Numba type of <class 'Struct'>
最小(工作)示例:
import numpy as np
import numba as nb
from struct import Struct
spec = [('type', nb.typeof(np.double)), ('h', nb.typeof(Struct(">f8")))]
@nb.jitclass(spec)
class TestClass:
def __init__(self):
self.type = np.double
self.h = Struct(">f8")
当我尝试编译上述类时,出现以下错误:
C:>python classtest.py
Traceback (most recent call last):
File "classtest.py", line 5, in <module>
spec = [('type', nb.typeof(np.double)), ('h', nb.typeof(Struct(">f8")))]
File "C:\ProgramData\Anaconda3\lib\site-packages\numba\typing\typeof.py", line
34, in typeof
raise ValueError(msg)
ValueError: ←[1mcannot determine Numba type of <class 'type'>←[0m
解决方案
如何将 numpy.double、numpy.single 和 struct.Struct 类型的类属性转换为各自的 numba 类型,以便能够在 jitclass 中使用这些属性?
对于numpy.double
和numpy.single
它很容易,numba.float64
并且numba.float32
是相应的 numba 类型。
在版本 0.43.1 中numba.typeof
也适用于 NumPy 类型,但是该函数需要一个实例而不是类本身:
>>> import numpy as np
>>> import numba as nb
>>> nb.__version__
'0.43.1'
>>> nb.typeof(np.double(10))
float64
但是,目前(从 numba 的 0.43.1 版开始)不支持struct
in numba(请参阅numba 文档的“2.6。支持的 Python 功能”),因此您不能struct
在 numba(包括jitclass
)中使用 nopython 模式。
当然,您可以将 struct 解压缩到各个组件中,如果 numba 支持它们,请改用它们。例如,'dd'
您可以numba.float64
在jitclass
. 由于您一直在使用不同的结构,并且 numba 并非支持每种 Python 类型,您可能需要对此进行试验。
推荐阅读
- python - ValueError:无法将输入数组从形状(10,1)广播到形状(10)
- python - 有没有办法简化这个 python 代码?
- c++ - 如何将输出数字分为奇数和偶数?
- python - 如何使用 boto3 获取用户的当前密码年龄
- java - 访问 getter 是私有的类的字段
- c++ - 打印所有 A 链表的元素 (C++)
- android - Proguard 功能和配置
- python - 使用数据类和字典来解决“盒子问题”
- android - 红米 Note 4 中的 ARCORE
- node.js - 如何使用 Chartjs + Nodejs + Express + Api 消耗在服务器端实时生成图表?