python可以处理矩阵吗_Python 稀疏矩阵处理

一、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]

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值