scipy中的csr_matrix

scipy中有个csr_matrix,可以简便地表达大规模稀疏矩阵。打个比方,对于1000*1000的二维矩阵,怎么表达呢?用一个numpy array去存储吗?其实,如果这个矩阵非常稀疏,比如特征矩阵等,可以用更简便的csr matrix去表达。

from scipy.sparse import csr_matrix
x = [0,0,0,0,1,1,1,1,2,2,2,2,3,3,3,3]
y = [0,1,2,3,0,1,2,3,0,1,2,3,0,1,2,3]
value = [1,0,3,0,0,0,0,1,0,9,1,0,0,0,0,1]
mat = csr_matrix((value,(x,y)),shape=(4,4))
print(mat)
print(mat.todense())

输出为:

  (0, 0)        1
  (0, 1)        0
  (0, 2)        3
  (0, 3)        0
  (1, 0)        0
  (1, 1)        0
  (1, 2)        0
  (1, 3)        1
  (2, 0)        0
  (2, 1)        9
  (2, 2)        1
  (2, 3)        0
  (3, 0)        0
  (3, 1)        0
  (3, 2)        0
  (3, 3)        1
[[1 0 3 0]
 [0 0 0 1]
 [0 9 1 0]
 [0 0 0 1]]

上面展示的是一个4x4情况下的csr matrix的表达形式。

发布了147 篇原创文章 · 获赞 1858 · 访问量 90万+

猜你喜欢

转载自blog.csdn.net/leviopku/article/details/102889734