您的数据布局非常不寻常。以下是我尝试使用它的第一步。
In [565]: M = sparse.lil_matrix((2,4), dtype=int)
In [566]: M
Out[566]:
<2x4 sparse matrix of type '<class 'numpy.int32'>'
with 0 stored elements in LInked List format>
In [567]: for i,row in enumerate(alist):
...: for col in row:
...: M[i, col[0]] = col[1]
...:
In [568]: M
Out[568]:
<2x4 sparse matrix of type '<class 'numpy.int32'>'
with 3 stored elements in LInked List format>
In [569]: M.A
Out[569]:
array([[ 0, 10, 0, -3],
[ 0, 0, 12, 0]])
是的,这是迭代的;lil
是最好的格式。
或者使用常见的输入样式coo
:
In [580]: data,col,row = [],[],[]
In [581]: for i, rr in enumerate(alist):
...: for cc in rr:
...: row.append(i)
...: col.append(cc[0])
...: data.append(cc[1])
...:
In [582]: data,col,row
Out[582]: ([10, -3, 12], [1, 3, 2], [0, 0, 1])
In [583]: M1=sparse.coo_matrix((data,(row,col)),shape=(2,4))
In [584]: M1
Out[584]:
<2x4 sparse matrix of type '<class 'numpy.int32'>'
with 3 stored elements in COOrdinate format>
In [585]: M1.A
Out[585]:
array([[ 0, 10, 0, -3],
[ 0, 0, 12, 0]])
另一种选择是创建空的
lil
矩阵,并直接填写其属性:
换句话说,从以下内容开始:
In [591]: m.data
Out[591]: array([[], []], dtype=object)
In [592]: m.rows
Out[592]: array([[], []], dtype=object)
并将它们改为:
In [587]: M.data
Out[587]: array([[10, -3], [12]], dtype=object)
In [588]: M.rows
Out[588]: array([[1, 3], [2]], dtype=object)
这仍然需要在您的alist
结构上进行2层迭代。
In [593]: for i, rr in enumerate(alist):
...: for cc in rr:
...: m.rows[i].append(cc[0])
...: m.data[i].append(cc[1])
In [594]: m
Out[594]:
<2x4 sparse matrix of type '<class 'numpy.int32'>'
with 3 stored elements in LInked List format>
In [595]: m.A
Out[595]:
array([[ 0, 10, 0, -3],
[ 0, 0, 12, 0]])
在另一条评论中,你提到理解 csr
indptr
的难度。最简单的方法是将这些格式之一转换为另一种格式:
In [597]: Mr=M.tocsr()
In [598]: Mr.indptr
Out[598]: array([0, 2, 3], dtype=int32)
In [599]: Mr.data
Out[599]: array([10, -3, 12])
In [600]: Mr.indices
Out[600]: array([1, 3, 2], dtype=int32)