什么时候可以在 numba 中使用 numpy 数组作为 dict 值?

问题描述 投票:0回答:1

我对 numba 字典的类型规则感到困惑。这是一个有效的 MWE:

import numpy as np
import numba as nb

    @nb.njit
    def foo(a, b, c):
        d = {}
        d[(1,2,3)] = a
        return d
    
    a = np.array([1, 2])
    b = np.array([3, 4])
    t = foo(a, b, c)

但是如果我按如下方式更改 foo 的定义,则会失败:

    @nb.njit
    def foo(a, b, c):
        d = {}
        d[(1,2,3)] = np.array(a)
        return d
TypingError: Failed in nopython mode pipeline (step: nopython frontend)
No implementation of function Function(<built-in function array>) found for signature:

 >>> array(array(int64, 1d, C))
 
There are 2 candidate implementations:
      - Of which 2 did not match due to:
      Overload in function 'impl_np_array': File: numba/np/arrayobj.py: Line 5384.
        With argument(s): '(array(int64, 1d, C))':
       Rejected as the implementation raised a specific error:
         TypingError: Failed in nopython mode pipeline (step: nopython frontend)
       No implementation of function Function(<intrinsic np_array>) found for signature:
        
        >>> np_array(array(int64, 1d, C), none)
        
       There are 2 candidate implementations:
             - Of which 2 did not match due to:
             Intrinsic in function 'np_array': File: numba/np/arrayobj.py: Line 5358.
               With argument(s): '(array(int64, 1d, C), none)':
              Rejected as the implementation raised a specific error:
                TypingError: array(int64, 1d, C) not allowed in a homogeneous sequence
         raised from /home/raph/python/mypython3.10/lib/python3.10/site-packages/numba/core/typing/npydecl.py:482
       
       During: resolving callee type: Function(<intrinsic np_array>)
       During: typing of call at /home/raph/python/mypython3.10/lib/python3.10/site-packages/numba/np/arrayobj.py (5395)
       
       
       File "../../python/mypython3.10/lib/python3.10/site-packages/numba/np/arrayobj.py", line 5395:
           def impl(object, dtype=None):
               return np_array(object, dtype)
               ^

  raised from /home/raph/python/mypython3.10/lib/python3.10/site-packages/numba/core/typeinfer.py:1086

During: resolving callee type: Function(<built-in function array>)
During: typing of call at <ipython-input-99-e05437a34ab9> (4)


File "<ipython-input-99-e05437a34ab9>", line 4:
def foo(a, b, c):
    <source elided>
    d = {}
    d[(1,2,3)] = np.array(a)
    ^

这是为什么?

python numba
1个回答
0
投票

这与 numba 处理 dict 的方式没有任何关系。这段代码失败并出现相同的错误:

@nb.njit
def foo2(a, b, c):
    x = np.array(a)
    return x

当您查看错误消息时,您会发现 numba 不知道如何从其他

np.array
初始化
np.array
:

No implementation of function Function(<built-in function array>) found for signature:
 
 >>> array(array(int64, 1d, C))

如果将代码更改为:

@nb.njit
def foo2(a, b, c):
    x = np.array([*a])
    return x

编译成功。

© www.soinside.com 2019 - 2024. All rights reserved.