有没有一种有效的方法可以将dask.array的每一行(或每一列)乘以一个向量元素?

时间:2020-02-07 22:27:06

标签: python arrays numpy dask

我在dask中有一个(巨大的)2D数组,它无法容纳在内存中,并且需要将每列乘以相应数量的向量。即,我想映射M(i,j)→x(i)* M(i,j)。

我认为没有任何方法可以直接修改元素。这在numpy中非常容易做到,但是看起来像乘快法则不允许这样做。

我目前的计划是从向量中创建一个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使用。有没有更简单的方法可以做到这一点?

1 个答案:

答案 0 :(得分:1)

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

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