稀疏矩阵中通常包含很多0,为了节省空间因而一般只保留非零元素。常见的稀疏矩阵有许多存储方法,详见:https://zhuanlan.zhihu.com/p/37525925 https://blog.csdn.net/jeffery0207/article/details/100064602 此处只简单介绍三种:COO、CSR和CSC。
COO:coordinate format:直接存储稀疏矩阵非零元素的坐标和值。占用空间大小3*n,其中n为原始矩阵中非零元素个数。 python代码实现:
from scipy import sparse import numpy as np data = [[1, 0, 0], [0, 2, 0], [0, 0, 3]] data = np.array(data) test = sparse.coo_matrix(data)原始矩阵: COO存储后的结果:
CSR:compressed sparse row:使用三个数组,其中两个n维数组存储非零元素的值和其对应的列索引。再使用一个r+1维数组存储原始矩阵中每行非零元素在上述n维数组中的索引,其中r为原始稀疏矩阵行数。
test = sparse.csr_matrix(data) #python实现将data转化为csr存储。原始矩阵data:
将csr表示的数组转化为矩阵
indptr = np.array([0, 2, 3, 6]) indices = np.array([0, 2, 2, 0, 1, 2]) data = np.array([1, 2, 3, 4, 5, 6]) sparse.csr_matrix((data, indices, indptr), shape=(3, 3)).toarray()csc:与csr刚好相反,是压缩列。其对应的python方法为csc_matrix()
参考文献: https://docs.scipy.org/doc/scipy/reference/generated/scipy.sparse.csr_matrix.html https://blog.csdn.net/gaoborl/article/details/82869858?utm_medium=distribute.pc_relevant.none-task-blog-BlogCommendFromMachineLearnPai2-1.compare&depth_1-utm_source=distribute.pc_relevant.none-task-blog-BlogCommendFromMachineLearnPai2-1.compare