我有稀疏的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 回答
你的flatMatrix是(3,4);每一行是[1 3 2 4] . 如果子矩阵是
x
,那么该行是x.A.T.flatten()
.F
是相同的(dtype是int) . 我必须将每个子矩阵转换为lil
,因为csr
尚未实现reshape
(在我的sparse
版本中) . 我不知道其他格式是否有效 .理想情况下
sparse
会让你做整个范围的numpy
数组(或矩阵)操作,但它还没有 .考虑到这个例子中的小尺寸,我不会推测替代品的速度 .