【问题标题】:Empty set in a jitclass attributejitclass 属性中的空集
【发布时间】:2020-01-13 03:45:44
【问题描述】:

我需要创建一个set 作为jitclass 属性,并且它必须以空开头:

import numba as nb

@nb.jitclass([('foo', nb.types.Set(nb.f8))])
class Bar:
    def __init__(self):
        self.foo = set()

b = Bar()

但它失败了,因为 numba 不知道临时 set 变量包含的对象的类型:

Failed in nopython mode pipeline (step: nopython frontend)
Cannot infer the type of variable '$0.2' (temporary variable),
have imprecise type: set(undefined).

这可行:

import numba as nb

@nb.jitclass([('foo', nb.types.Set(nb.f8))])
class Bar:
    def __init__(self):
        self.foo = {0.}
        self.foo.clear()

b = Bar()

但是解决方案真的很丑。有没有更好的方法来初始化空的set

我正在使用 Python 3.6 和 Numba 0.45.1

【问题讨论】:

  • 这似乎是一个“功能请求”,可能也属于numba issue tracker
  • 是的,我希望能找到类似numba.typed.Dict.empty() 的东西,但从 Numba 0.64 开始,他们仍然说这是一个实验性功能。所以有一个“numba.typed.Set.empty()”需要更长的时间。

标签: python class set numba


【解决方案1】:

您不能在jitclasses 的__init__ 中实例化空的“Python 类”。列表也会出现同样的问题(从 numba 0.45.1 开始):

@nb.jitclass([('foo', nb.types.List(nb.f8))])
class Bar:
    def __init__(self):
        self.foo = []
TypingError: Failed in nopython mode pipeline (step: nopython frontend)
Failed in nopython mode pipeline (step: nopython frontend)
Cannot infer the type of variable '$0.1' (temporary variable), have imprecise type: list(undefined).

这里的问题是 numba 通过分析函数体来推断类型。它没有考虑类的规范。


我个人会创建一个函数包装器来创建空集,这样如果(或何时)numba 决定根据签名/规范实现创建空集,则更容易更改代码:

import numba as nb

@nb.njit
def create_empty_set_float64():
    aset = {1.}
    aset.clear()
    return aset

@nb.jitclass([('foo', nb.types.Set(nb.f8))])
class Bar:
    def __init__(self):
        self.foo = create_empty_set_float64()

b = Bar()

【讨论】:

  • 这似乎是正确的方法,而没有像 Dict.empty() 这样的集合。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2022-10-04
  • 2021-04-21
  • 1970-01-01
  • 2017-04-26
  • 1970-01-01
  • 2019-02-06
相关资源
最近更新 更多