首页 文章

Numpy / Scipy - 向量的稀疏矩阵

提问于
浏览
1

我有稀疏的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()

这确实令人不满意和不优雅 . 有没有人知道如何以有效的方式实现这一目标?

1 回答

  • 2

    你的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 数组(或矩阵)操作,但它还没有 .

    考虑到这个例子中的小尺寸,我不会推测替代品的速度 .

相关问题