numpy array如何转换成scipy的csr matrix
也就是说,一个dense的numpy矩阵,如何转换成scipy包里面的sparse的csr矩阵看代码:
import numpy as np
from scipy.sparse import csr_matrix
a = np.array([[1, 0, 0],[0,1,0],[0,1,1]])
print('a: ', a)
row, col = np.nonzero(a)
values = a[row, col]
csr_a = csr_matrix((values, (row, col)), shape=(3,3))
print('csr_a:',csr_a)
print('type: ',type(csr_a))
输出:
a: [[1 0 0]
[0 1 0]
[0 1 1]]
csr_a: (0, 0) 1
(1, 1) 1
(2, 1) 1
(2, 2) 1
type: <class 'scipy.sparse.csr.csr_matrix'>
反过来,从csr到dense的numpy array:
print(csr_a.toarray())
从csr到coo格式:
print(csr_a.tocoo())

656

被折叠的 条评论
为什么被折叠?



