繁体   English   中英

Numba 尝试:如果 array.shape[1] - 错误:元组索引超出范围。 没有 numba 的情况下工作,不适用于 @njit(fastmath=True, nogil=True, cache=True)

[英]Numba try: if array.shape[1] - error: tuple index out of range. works without numba, doesn't work with @njit(fastmath=True, nogil=True, cache=True)

Numba 0.53.1、Python 3.7.9、Windows 10 64 位

这个 doctest 工作正常:

import numpy as np

def example_numba_tri(yp):
    """
    >>> example_numba_tri(np.array([0.1, 0.5, 0.2, 0.3, 0.1, 0.7, 0.6, 0.4, 0.1]))
    array([[0.1, 0.3, 0.6],
           [0.5, 0.1, 0.4],
           [0.2, 0.7, 0.1]])
    """
    try:
        if yp.shape[1] == 3:
            pass
    except:
        yp = yp.reshape(int(len(yp) / 3), -1, order='F')

    return yp

只需添加@njit(fastmath=True, nogil=True, cache=True)

from numba import njit
import numpy as np

@njit(fastmath=True, nogil=True, cache=True)
def example_numba_tri(yp):
    """
    >>> example_numba_tri(np.array([0.1, 0.5, 0.2, 0.3, 0.1, 0.7, 0.6, 0.4, 0.1]))
    array([[0.1, 0.3, 0.6],
           [0.5, 0.1, 0.4],
           [0.2, 0.7, 0.1]])
    """
    try:
        if yp.shape[1] == 3:
            pass
    except:
        yp = yp.reshape(int(len(yp) / 3), -1, order='F')

    return yp

并得到一个错误:

    numba.core.errors.TypingError: Failed in nopython mode pipeline (step: nopython frontend)
    Internal error at <numba.core.typeinfer.StaticGetItemConstraint object at 0x0000020CB55A7608>.
    tuple index out of range
    During: typing of static-get-item at C:/U1/main.py (1675)
    Enable logging at debug level for details.
    
    File "main.py", line 1675:
    def example_numba_tri(yp):
        <source elided>
        try:
            if yp.shape[1] == 3:
            ^

如何解决它以及为什么会发生这种情况? 或者这是一个错误? 我读了 https://numba.pydata.org/numba-doc/dev/reference/pysupported.html#pysupported-exception-handling ,但似乎我做了所有事情,因为它写在那里。

更新:

  1. https://github.com/numba/numba/issues/6872
  2. 这对我也很有用https://numba.pydata.org/numba-doc/latest/user/troubleshoot.html#my-code-doesn-t-compile
  3. 分析和重构帮助我仅将大多数 CPU 密集型部件转换为 numba
  4. numba.pydata.org/numba-doc/dev/reference/numpysupported.html 似乎不支持orderorder='F'

请考虑以另一种方式重写您的代码,因为它看起来像您的 Numba 代码检查输入数据的类型,因此if yp.shape[1] == 3:在编译阶段被检查,则阻止它,这就是为什么它不被try except

请尝试下面的代码,它与您的代码相同,但没有order='F'不想以任何方式与 Numba 一起使用。

from numba import njit
import numpy as np


@njit(fastmath=True, nogil=True, cache=True)
def example_numba_tri(yp):
    return yp.reshape(int(len(yp) / 3), -1)


def wrapper_example_numba_tri(yp):
    if len(yp.shape) > 1:
        if yp.shape[1] == 3:
            return yp
    return example_numba_tri(yp)


if name == 'main':
    x = np.array([0.1, 0.5, 0.2, 0.3, 0.1, 0.7, 0.6, 0.4, 0.1])
    wrapper_example_numba_tri(x)

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM