我试图将一个函数应用到一个Dask数组。使用 apply_along_axis虽然同样的函数在numpy数组上有效,但在Dask数组上却无效。下面是一个例子。
import dask.array as da
w = numpy.array([[6,7,8],[9,10,11]])
q = numpy.array([[1,2,3],[4,5,6]])
s = numpy.stack([w,q])
def func(arr):
t, y = arr[0], arr[1]
return arr[0] + arr[1]
s_dask = da.from_array(s)
在numpy数组上运行func可以正常工作,而在Dask数组上运行则会抛出一个错误:"IndexError: index 1 is out of bounds for axis 0 with size 1"。IndexError: index 1 is out of bounds for axis 0 with size 1"(索引错误:索引1超出了0轴的范围)。
>>>s
array([[[ 6, 7, 8],
[ 9, 10, 11]],
[[ 1, 2, 3],
[ 4, 5, 6]]])
>>>numpy.apply_along_axis(func,0,s)
array([[ 7, 9, 11],
[13, 15, 17]])
>>>da.apply_along_axis(func,0,s_dask)
Traceback (most recent call last):
File "<pyshell#151>", line 1, in <module>
da.apply_along_axis(func,0,s_dask)
File "..Python37\lib\site-packages\dask\array\routines.py", line 383, in apply_along_axis
test_result = np.array(func1d(test_data, *args, **kwargs))
File "<pyshell#149>", line 2, in func
t, y = a[0],a[1]
IndexError: index 1 is out of bounds for axis 0 with size 1
我也不知道自己哪里做错了
Dask数组试图找出输出数组的dtype是什么。 为了做到这一点,它通过你的函数发送了一个小的空数组。 这个小空数组是失败的,因为你的函数假设输入的大小至少是2。
你可以通过显式提供 dtype 来节省 Dask 的麻烦。
da.apply_along_axis(func, 0, s_dask, dtype=s_dask.dtype)