一、Scipy
1.COO、CSC和CSRcoo_matrix(arg1[, shape, dtype, copy])A sparse matrix in COOrdinate format.
csc_matrix(arg1[, shape, dtype, copy])Compressed Sparse Column matrix
csr_matrix(arg1[, shape, dtype, copy])Compressed Sparse Row matrixcoo_matrix(arg1[, shape, dtype, copy])A sparse matrix in COOrdinate format.
csc_matrix(arg1[, shape, dtype, copy])Compressed Sparse Column matrix
csr_matrix(arg1[, shape, dtype, copy])Compressed Sparse Row matrixcoo_matrix(arg1[, shape, dtype, copy])A sparse matrix in COOrdinate format.
csc_matrix(arg1[, shape, dtype, copy])Compressed Sparse Column matrix
csr_matrix(arg1[, shape, dtype, copy])Compressed Sparse Row matrix
COO是coordinate的缩写,也就是说COO方法就是数据结构中记录稀疏矩阵的方法,即三元组形式。
CSC是压缩存储稀疏矩阵的类,其中的C就是指column,也就是按照列来压缩存储压缩矩阵。CSC是按列存储一个稀疏矩阵的。其中indptr中的数据代表矩阵中每一列所存的数据在data中的开始和结束的索引,例如这里indptr为[0, 2, 3, 6],即表示在data中,索引[0, 2)为第一列的数据,索引[2, 3)为第二列的数据,索引[3, 6)为第三列的数据。而indices中的数据代表所对应的data中的数据在其所在列中的所在行数,例如,这里的indices为[0, 2, 2, 0, 1, 2],表示在data中,数据1在第0行,数据2在第2行,数据3在第2行,数据4在第0行,数据5在第一行,数据6在第2行。从而建立起一个稀疏矩阵。
CSR与CSC类似,只不过R是指row,也就是按照行来进行压缩存储。
>>> 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()
array([[1, 0, 2],
[0, 0, 3],
[4, 5, 6]])CSR是按行来存储一个稀疏矩阵的,其原理与CSC类似。indptr中的数据表示矩阵中每一行的数据在data中开始和结束的索引,而indices中的数据表示所对应的在data中的数据在矩阵中其所在行的所在列数。可以看出,在indptr、indices和data三个数组相同的情况下,通过CSC和CSR分别表示出来的矩阵互为转置关系。
二、Pytorch
1.scipy.sparse矩阵转torch.sparse
# data_coo
values =data_coo.data
indices = np.vstack((data_coo.row,data_coo.col))
i = torch.LongTensor(indices)
v = torch.FloatTensor(values)
shape = data_coo.shape
X_train=torch.sparse.FloatTensor(i, v, torch.Size(shape))
参考:
[4]