gpt4 book ai didi

python - 从 numba 创建一个由 njit 装饰的 numpy 数组

转载 作者:太空宇宙 更新时间:2023-11-04 02:10:14 24 4
gpt4 key购买 nike

代码在这里:

import numba as nb
import numpy as np

@nb.njit
def func(size):
ary = np.array([np.arange(size),np.arange(size)+1,np.arange(size)-1]).T
X = np.array([ary[1:,0] - ary[:-1,2],
ary[1:,1] - ary[:-1,2],
ary[1:,0] - ary[1:,1]
])
return X

Z = func(10**9)

当我运行代码时,它给了我一条错误消息,我真的不明白这里发生了什么。 njit修饰的函数不支持在函数内部新建数组吗?错误信息如下:

TypingError: Invalid use of Function(<built-in function array>) with argument(s) of type(s): (list(array(int64, 1d, C)))
* parameterized
In definition 0:
TypingError: array(int64, 1d, C) not allowed in a homogeneous sequence
raised from C:\Users\User\Anaconda3\lib\site-packages\numba\typing\npydecl.py:459
In definition 1:
TypingError: array(int64, 1d, C) not allowed in a homogeneous sequence
raised from C:\Users\User\Anaconda3\lib\site-packages\numba\typing\npydecl.py:459
This error is usually caused by passing an argument of a type that is unsupported by the named function.
[1] During: resolving callee type: Function(<built-in function array>)
[2] During: typing of call at C:/Users/User/Desktop/all python file/3.2.4/nb_datatype.py (65)

编辑:我忘记在编辑前转置数组,它应该是一个 10^9 x 3 的数组。

最佳答案

numba.njit 不支持通过 NumPy 数组列表或列表列表来实例化 NumPy 数组。相反,使用 np.empty然后通过 NumPy 索引分配值:

@nb.njit
def func(size):
row_count = 3
ary = np.empty((row_count, size))
ranger = np.arange(size)
ary[0] = ranger
ary[1] = ranger + 1
ary[2] = ranger - 1

X = np.empty((row_count, row_count - 1))
X[0] = ary[1:,0] - ary[:-1,2]
X[1] = ary[1:,1] - ary[:-1,2]
X[2] = ary[1:,0] - ary[1:,1]

return X

Z = func(10**2)

print(Z)

array([[-1., -4.],
[ 0., -3.],
[-1., -1.]])

关于python - 从 numba 创建一个由 njit 装饰的 numpy 数组,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53861099/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com