用scipy库生成稀疏矩阵
方法一:
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. ]]
方法二:
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]]