[英]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 64bit Numba 0.53.1、Python 3.7.9、Windows 10 64 位
This doctest works fine:这个 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
Just add @njit(fastmath=True, nogil=True, cache=True)
:只需添加@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
and get an error:并得到一个错误:
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:
^
How to fix it and why this happen?如何解决它以及为什么会发生这种情况? Or this is a bug?或者这是一个错误? I read https://numba.pydata.org/numba-doc/dev/reference/pysupported.html#pysupported-exception-handling , but seems I did everything as it written there.我读了 https://numba.pydata.org/numba-doc/dev/reference/pysupported.html#pysupported-exception-handling ,但似乎我做了所有事情,因为它写在那里。
Updates:更新:
order
( order='F'
) numba.pydata.org/numba-doc/dev/reference/numpysupported.html 似乎不支持order
( order='F'
) Please consider to rewrite your code another way, since it looks like your Numba code checks types of input data so block if yp.shape[1] == 3:
is checked in compilation stage, that is why it is not handled by try except
请考虑以另一种方式重写您的代码,因为它看起来像您的 Numba 代码检查输入数据的类型,因此if yp.shape[1] == 3:
在编译阶段被检查,则阻止它,这就是为什么它不被try except
Please try the code below, it is identical to your code, but there is no order='F'
which does not want to work with Numba in any way.请尝试下面的代码,它与您的代码相同,但没有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.