python - 有没有一种有效的方法将 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。有没有更简单的方法来做到这一点?
解决方案
像下面的例子那样做是行不通的?
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
推荐阅读
- python-2.7 - 在 python 中用海龟创建网格
- python - 使用无服务器框架进行本地开发
- python-3.x - 避免调试装饰器,而只调试装饰器
- ios - 如何在 PercentEncoding 中只编码所有特殊字符是 swift 5
- javascript - 使用 JS 删除 facebook 像素 cookie
- typescript - 如何从“导出模块”块导入类型?
- java - 并行运行测试时输出一次日志文件横幅
- jsp - JSP表单如果存在,如何根据url添加参数?
- azure-devops - Azure DevOps Yaml 获取时间并增加小时数
- python - 在 Python 中初始化两个变量以指向相同的引用