无法使用循环修改作为参数传递的1d numpy数组



我对numba循环和1d numpy数组感到头疼,似乎找不到解释。基本上,我的目标是使用作为参数传递的函数,与numba循环并行地传递修改numpy数组。它与2d numpy数组配合使用效果很好,但由于某些原因,它与简单的1d numpy数组不配合使用。这是重现问题的代码:

import numpy as np
import numba as nb
size = 10

# Define a 1d numpy array
vec_test_1 = np.zeros(size)
# Fill the 1d array with values
for i in range(size):
vec_test_1[i] = float(i)

# Function that modifies and element
@nb.jit(nopython = True)
def func1(xyz):
xyz = xyz + 2.47

# Loop with numba to modify all elements of the array
@nb.jit(nopython = True, parallel = True)
def loop_numba(vec, func):
for i in nb.prange(len(vec)):
func(vec[i])

loop_numba(vec_test_1, func1)

此循环后vec_test_1保持不变:

array([0., 1., 2., 3., 4., 5., 6., 7., 8., 9.])

应该在什么时候:

array([ 2.47,  3.47,  4.47,  5.47,  6.47,  7.47,  8.47,  9.47, 10.47,
11.47])

令我惊讶的是,当作为参数传递的数组是2d数组时,它工作得很好。我可以用numba循环修改它的所有元素。

有人能帮我理解这个问题吗?

您必须定义一个返回值,因为您在传递给函数时会复制各个元素。

说明:在此处找到。

基本上:您将一个单一的、不可变的元素传递给函数,因此它是通过复制传递的(创建了一个副本,在函数中进行了更改(。如果使用2D数组,那么对于python来说,这是一个可变的对象,因此它是通过引用传递的。如果现在对其进行操作,则基础引用将发生更改,并且这在函数外部的结果中可见。

import numpy as np
import numba as nb
size = 10
# Define a 1d numpy array
vec_test_1 = np.arange(size, dtype=np.float32)
# Function that modifies and element
@nb.jit(nopython = True)
def func1(xyz):
xyz = xyz + 2.47
return xyz
# Loop with numba to modify all elements of the array
@nb.jit(nopython = True, parallel = True)
def loop_numba(vec, func):
for i in nb.prange(len(vec)):
vec[i] = func(vec[i])
loop_numba(vec_test_1, func1)
In [2]: vec_test_1
Out[2]: 
array([ 2.47,  3.47,  4.47,  5.47,  6.47,  7.47,  8.47,  9.47, 10.47,
11.47], dtype=float32)

此外:我将矢量初始化更改为np.arange(size, dtype=float),以便于理解。

最新更新