首页 > 解决方案 > 有没有一种有效的方法将 dask.array 的每一行(或列)乘以向量元素?

问题描述

我在 dask 中有一个(巨大的)二维数组,它不适合内存,并且需要将每一列乘以相应数量的向量。即,我想映射 M(i,j) → x(i)*M(i,j)。

我认为没有任何方法可以直接在 dask 中修改元素。这在 numpy 中非常容易做到,但看起来 dask multiply 不允许以同样的方式实现它。

我目前的计划是从向量制作一个 dask 数组,并映射一个零矩阵(与原始矩阵大小相同)以重复​​向量块并将它们传回。

M = da.from_array( the_matix  , chunks = chunks )
x = da.from_array( the_vector , chunks = chunks ) 

def fn(x, block_id=None): 
   ret = x.blocks[ block_id[0] ].compute()
   ret = np.repeat( ret[:,np.newaxis] , M.shape[1] , axis = 1 )
   return ret

temp = da.zeros( chunks=M.chunks , shape=M.shape )
temp = temp.map_blocks( fn , dtype=float )
M = da.multiply( [ M , temp ] ) 

不过,这似乎效率极低,而且对于这样一个简单的任务,需要大量使用 RAM。有没有更简单的方法来做到这一点?

标签: pythonarraysnumpydask

解决方案


像下面的例子那样做是行不通的?

from dask.array import from_array, multiply
from numpy import array
M = from_array(array([[0,1,2,3,4],[5,6,7,8,9],[10,11,12,13,14]]))
vector = from_array(array([1,2,3]))
multiply(M.T, vector).T.compute()

输出 :

array([[ 0,  1,  2,  3,  4],
       [10, 12, 14, 16, 18],
       [30, 33, 36, 39, 42]])

我已经检查过它也适用于:

import dask.array as da
M = da.random.random((10000, 10000), chunks=(1000, 1000))
vector = da.random.random((10000, 1), chunks=(1000, 1000))
result = multiply(M.T, vector).T

推荐阅读