from scipy import sparse
import numpy as np
x = np.array([[1,2,3],[4,5,6]]) #利用numpy创建一个数组
eye = np.eye(4) #创建一个4维单位向量
print('x:\n{}'.format(x))
print('eye:\n{}'.format(eye))

##稀疏矩阵是指0元素的个数远远小于非0元素
#可以通过numpy数组创建scipy稀疏矩阵,即只保留非0元素,并给出其位置,减少所用内存
sparse_matrix = sparse.csr_matrix(eye)
print('sparse_matrix:\n{}'.format(sparse_matrix))

#创建稀疏矩阵的另一个方法
data = np.ones(4)
row_indices = np.arange(4) #创建一个[0,1,2,3]的数组
col_indices = np.arange(4)
sparse_matrix = sparse.coo_matrix((data,(row_indices,col_indices)))
print('sparse_matrix:\n{}'.format(sparse_matrix))

2329

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



