用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]] |
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】凌霞软件回馈社区,博客园 & 1Panel & Halo 联合会员上线
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】博客园社区专享云产品让利特惠,阿里云新客6.5折上折
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步