【发布时间】:2020-07-11 06:56:25
【问题描述】:
我正在尝试使用 Numba 编译以下函数:
@njit(fastmath=True, nogil=True)
def generate_items(array, start):
array_positions = np.empty(SIZE, dtype=np.int64)
count = 0
while count < SIZE - start:
new_array = mutate(np.empty(0, dtype=np.uint8))
if len(new_array) > 0:
array_positions[count] = len(array) # <<=== FAILS HERE
array = np.append(array, np.append(new_array, 255))
count += 1
return array, array_positions
但它在上面指示的行上失败并显示以下错误消息:
numba.core.errors.TypingError: Failed in nopython mode pipeline (step: nopython frontend)
Cannot unify array(uint8, 1d, C) and array(int64, 1d, C) for 'array.3', defined at ...
这似乎没有意义,因为我只是将 int(len 上的结果)分配给具有 dtype 或 np.int64 的数组?
请注意,array 的类型为 np.uint8 - 但我没有分配数组本身,所以这条消息对我来说毫无意义。
我尝试对此进行重构:
tmp = len(array) # <<=== FAILS HERE
array_positions[count] = tmp
但是它在那里失败了......同样的消息。
我还尝试用array.size 替换len(array),因为这是一个一维数组,但同样的错误。
谁能明白为什么会失败?
我使用的是 Python 3.7 和 Numba 0.50
谢谢!
【问题讨论】:
-
不,这是一个不同的问题。我没有在这种情况下使用连接。
-
np.append使用np.concatenate。我不确定numba,但在循环中使用np.append(或任何连接/堆栈系列)是一个坏主意——速度慢,而且通常很难正确处理。我们建议将数组收集在一个列表中,并在最后进行 一个 连接。 -
花几分钟看看
np.append的python代码。你会看到,即使在numpy中,它也不是一个很好的功能。另一件事,当在numba中使用concatenate时,给它一个元组参数,而不是一个列表。
标签: python python-3.x numpy numba