【问题标题】:How returning a string when using jitclass from numba?从 numba 使用 jitclass 时如何返回字符串?
【发布时间】:2017-12-04 23:31:55
【问题描述】:

当我在使用jitclass 的类中调用函数时,我试图返回一个字符串,但出现错误:

numba.errors.InternalError: Failed at nopython (nopython mode backend)
cannot convert native const('Something') to Python object
[1] During: resolving callee type: BoundFunction((<class 'numba.types.misc.ClassInstanceType'>, 'get_Names') for     instance.jitclass.myclass#3f2d488<A:float64,B:float64>)
[2] During: typing of call at <string> (3)

我正在使用这段代码来测试功能:

from numba import jitclass
from numba import boolean, int32, float64,uint8

spec = [('A' ,float64),
        ('B' ,float64)]

@jitclass(spec)
class myclass:

    def __init__(self,):
        self.A = 3.25
        self.B = 22.5

    def get_Names(self):
        return "Something"



mC = myclass()
print(mC.get_Names())

有人知道我如何返回字符串吗?

【问题讨论】:

  • 目前 numba 不支持此功能,nopython 模式通常也不支持字符串(从版本 0.36 开始编写)
  • 是的,我明白这一点。但也许存在解决方法。也许基于 uint8 数组或类似的东西?

标签: python jit numba


【解决方案1】:

您可以通过使用字节数组来表示字符串来解决这个问题,如下所示。

也就是说,我认为这很难看/很难维护。假设它适合这个问题,我认为你最好使用带有jit函数的普通python类来加速,或者使用像cython这样的东西,它对扩展类型有更丰富的支持。

from numba import jitclass, float64

SOMETHING = np.frombuffer(b"Something", dtype='uint8')

spec = [('A' ,float64),
        ('B' ,float64)]

def get_jitclass_str(val):
    return bytes(val).decode('utf-8')

@jitclass(spec)
class myclass:

    def __init__(self,):
        self.A = 3.25
        self.B = 22.5

    def get_Names(self):
        return SOMETHING

用法

In [16]: mc = myclass()

In [17]: get_jitclass_str(mc.get_Names())
Out[17]: 'Something'

【讨论】:

  • 听起来很有希望。但是在您编写的代码中。字符串“Something”不能更改。在我的脚本中,字符串是原位生成的。那么它就是一个变量。是否也可以获得在 myclass 中修改的字符串?我的问题可能没有得到很好的解释。
  • 如果您想从一组枚举选项中返回,那么是的,这很容易,只需添加更多全局变量即可。如果它是真正动态生成的,那么是的,仍然有可能,但更麻烦的是你必须使用字节的整数表示来构建它。
猜你喜欢
  • 1970-01-01
  • 2016-12-05
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2021-03-12
  • 2021-04-21
  • 1970-01-01
相关资源
最近更新 更多