https://docs.scipy.org/doc/scipy-0.14.0/reference/generated/scipy.sparse.coo_matrix.tocsr.html
https://docs.scipy.org/doc/scipy/reference/generated/scipy.io.mmread.html
1.这个包是真的很厉害啊!
>>> from numpy import array >>> from scipy.sparse import coo_matrix >>> row = array([0,0,1,3,1,0,0]) >>> col = array([0,2,1,3,1,0,0]) >>> data = array([1,1,1,1,1,1,1]) >>> A = coo_matrix( (data,(row,col)), shape=(4,4)).tocsr() >>> A.todense() matrix([[3, 0, 1, 0], [0, 2, 0, 0], [0, 0, 0, 0], [0, 0, 0, 1]])
直接根据行index,列index,以及data建立索引,A就是稀疏数据的类型:
<4x4 sparse matrix of type '<class 'numpy.float32'>' with 3 stored elements in Compressed Sparse Row format>
压缩稀疏行格式。
2.从文件中读取mtx格式数据并存储为稀疏格式
count内容:
%%MatrixMarket matrix coordinate integer general
4 4 4
1 1 1
1 2 1
1 1 1
2 3 1
这里针对第一行,应该是mtx文件的必要格式,需要5列内容。第二行表示的意思分别是:rows,cols,total_nums。
注意行号和列号都不是从0开始,而是从1,这和计算机中的习惯并不一样,大概是为了更多领域来用这个包吧。
from numpy import array from scipy.io import mmread count = mmread('a.mtx').T.tocsr().astype('float32') #输出: >>> count <4x4 sparse matrix of type '<class 'numpy.float32'>' with 3 stored elements in Compressed Sparse Row format> >>> count.todense() matrix([[2., 0., 0., 0.], [1., 0., 0., 0.], [0., 1., 0., 0.], [0., 0., 0., 0.]], dtype=float32)