Skip to main content
 首页 » 编程设计

python之在 dask 数组上并行化 numpy arange

2025年01月19日12pengyingh

我想用dask来做下面的操作;假设我有一个 numpy 数组:
在:x = np.arange(5)
输出:[0,1,2,3,4]
然后我想要一个函数将 np.arange 映射到我数组的所有元素。 我已经为此定义了一个函数:

def list_range(array, no_cell): 
    return np.add.outer(array, np.arange(no_cell)).T 
 
# e.g 
In: list_range(x,3) 
Out: array([[0, 1, 2, 3, 4], 
       [1, 2, 3, 4, 5], 
       [2, 3, 4, 5, 6]]) 

现在我想在 dask 数组上使用 map_blocks 并行重现它,但我总是遇到错误。这是我基于 dask documentation 的尝试 map block 的数量:

constant = 4 
d = da.arange(5, chunks=(2,)) 
f = da.core.map_blocks(list_range, d, constant, chunks=(2,)) 
f.compute() 

我明白了 ValueError:无法将输入数组从形状 (4,2) 广播到形状 (4)

请您参考如下方法:

你检查过 Dask 的 ufunc 了吗?方法?针对你的问题,你可以试试,

da.add.outer(d, np.arange(constant)).T.compute() 

在使用 map_blocks 时,您必须确保在操作导致 block 维度发生变化时指定新的维度。在您的问题中, block 维度不再是 (2,),而是 (2,4)。应使用 new_axis 参数指定此新维度。另外,我发现 map_blocks 没有在 map_blocks 之后对 block 进行 vstacking,我无法让转置在映射函数中工作。试试这个让 map_blocks 工作,

def list_range(array, no_cell): 
    return np.add.outer(array, np.arange(no_cell)) 
 
constant = 4 
d = da.arange(5, chunks=(2,)) 
 
 
f=da.core.map_blocks(list_range, d, constant, chunks=(2,constant), new_axis=[1]) 
f.T.compute()