【问题标题】:Numpy / Scipy - Sparse matrix to vectorNumpy / Scipy - 稀疏矩阵到向量
【发布时间】:2014-06-26 21:12:47
【问题描述】:

我有稀疏的 CSR 矩阵(来自两个稀疏向量的乘积),我想将每个矩阵转换为平面向量。实际上,我想避免使用任何密集表示或迭代索引。

到目前为止,唯一的解决方案是使用 coo 表示来迭代非 null 元素:

import numpy
from scipy import sparse as sp
matrices = [sp.csr_matrix([[1,2],[3,4]])]*3
vectorSize = matrices[0].shape[0]*matrices[0].shape[1]
flatMatrixData = []
flatMatrixRows = []
flatMatrixCols = []
for i in range(len(matrices)):
    matrix = matrices[i].tocoo()
    flatMatrixData += matrix.data.tolist()
    flatMatrixRows += [i]*matrix.nnz
    flatMatrixCols += [r+c*2 for r,c in zip(matrix.row, matrix.col)]
flatMatrix = sp.coo_matrix((flatMatrixData,(flatMatrixRows, flatMatrixCols)), shape=(len(matrices), vectorSize), dtype=numpy.float64).tocsr()

这确实令人不满意且不雅。有谁知道如何以有效的方式实现这一目标?

【问题讨论】:

  • 你的flatMatrix 是 (3,4);每行是[1 3 2 4]。如果子矩阵是x,那么该行是x.A.T.flatten()

标签: numpy scipy sparse-matrix


【解决方案1】:

你的 flatMatrix 是 (3,4);每行是 [1 3 2 4]。如果子矩阵为x,则该行为x.A.T.flatten()

F = sp.vstack([x.T.tolil().reshape((1,vectorSize)) for x in matrices])

F 相同(dtype 为 int)。我必须将每个子矩阵转换为lil,因为csr 没有实现reshape(在我的sparse 版本中)。我不知道其他格式是否有效。

理想情况下,sparse 可以让您执行所有numpy 数组(或矩阵)操作,但目前还没有。

鉴于此示例中的小尺寸,我不会推测替代方案的速度。

【讨论】:

  • 太好了,这正是我想要的。正如您所指出的,flatten()reshape() 不适用于大多数稀疏矩阵。我不知道 lil 矩阵可以被重塑。谢谢!
猜你喜欢
  • 2017-03-26
  • 1970-01-01
  • 1970-01-01
  • 2013-11-13
  • 2016-06-16
  • 1970-01-01
  • 1970-01-01
  • 2014-12-21
  • 2016-01-24
相关资源
最近更新 更多