用scipy库生成稀疏矩阵

方法一:

1
2
3
4
5
6
7
8
import scipy as spy
from scipy.sparse import csc_matrix
 
m = 2
n = 3
A = spy.sparse.rand(m, n, density=0.5, format='csc', dtype=None).toarray()
print(A)   # [[0.         0.12812445 0.23608898]
           #  [0.99904052 0.         0.        ]]

 

方法二:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
import scipy as spy
from scipy.sparse import csc_matrix
 
m = 2
n = 3
A = spy.sparse.rand(m, n, density=0.5, format='csc', dtype=None)
print(A)   #  (0, 0)    0.538816734003357
           #  (0, 1)    0.39676747423066994
           #  (1, 2)    0.4191945144032948
 
print(A.nonzero())  # (array([0, 0, 1], dtype=int32), array([0, 1, 2], dtype=int32))
print(A.data)       # [0.53881673 0.39676747 0.41919451]
 
matrix = csc_matrix((A.data, (A.nonzero()[0], A.nonzero()[1])), shape=(m, n)).toarray()
print(matrix)       # [[0.53881673 0.39676747 0.        ]
                    #  [0.         0.         0.41919451]]

 

posted @   Picassooo  阅读(376)  评论(0编辑  收藏  举报
努力加载评论中...
点击右上角即可分享
微信分享提示