【发布时间】:2016-04-15 15:31:47
【问题描述】:
我有一个大的稀疏矩阵 globalGrid (lil_matrix) 和一个较小的矩阵 localGrid (coo_matrix)。 localGrid 代表 globalGrid 的一个子集,我想用 localGrid 更新 globalGrid。为此,我使用以下代码(在 Python Scipy 中):
globalGrid[xLocalgrid:xLocalgrid + localGrid.shape[0], yLocalgrid: yLocalgrid + localGrid.shape[1]] = localGrid
其中 xLocalGrid 和 yLocalGrid 是 localGrid 原点相对于 globalGrid 的偏移量。
问题是localGrid是稀疏的,而且零元素也分配给globalGrid。有没有办法只能分配存储的元素而不是 0 元素?
我在 numpy 中发现了掩码数组,但这似乎不适用于稀疏 scipy 矩阵。
编辑:针对下面的cmets,这里有一个例子来说明我的意思:
首先设置矩阵:
M=sparse.lil_matrix(2*np.ones([5,5]))
m = sparse.eye(3)
M.todense()
matrix([[ 2., 2., 2., 2., 2.],
[ 2., 2., 2., 2., 2.],
[ 2., 2., 2., 2., 2.],
[ 2., 2., 2., 2., 2.],
[ 2., 2., 2., 2., 2.]])
m.todense()
matrix([[ 1., 0., 0.],
[ 0., 1., 0.],
[ 0., 0., 1.]])
然后赋值:
M[1:4, 1:4] = m
现在结果是:
M.todense()
matrix([[ 2., 2., 2., 2., 2.],
[ 2., 1., 0., 0., 2.],
[ 2., 0., 1., 0., 2.],
[ 2., 0., 0., 1., 2.],
[ 2., 2., 2., 2., 2.]])
而我需要的结果是:
matrix([[ 2., 2., 2., 2., 2.],
[ 2., 1., 2., 2., 2.],
[ 2., 2., 1., 2., 2.],
[ 2., 2., 2., 1., 2.],
[ 2., 2., 2., 2., 2.]])
【问题讨论】:
-
此分配是否有效,
globalGrid中的值正确?您是否担心结果中有不必要的 0 项?你看到那些我的.data属性了吗?您可能需要显示示例矩阵。 -
您能给我们一个minimal reproducible example 和确切的预期输出吗?
-
我在问题中添加了一个我想要实现的示例。
标签: python numpy matrix scipy sparse-matrix