python scipy.sparse稀疏矩阵

官方文档的搬运工
https://docs.scipy.org/doc/scipy/reference/sparse.html

几种常见的稀疏矩阵类型

coo_matrix

COO是构建稀疏矩阵的快速格式,可以转化为CSR或者CSC后进行快速的矩阵运算,本质是只储存矩阵中有值的数据

from scipy.sparse import coo_matrix,csr_matrix,csc_matrix

最常使用的构造方式:输入为ijv三个向量

# row代表横坐标i,col代表纵坐标j,data表示对应坐标点的值,
row = np.array([0, 3, 1, 0])
col = np.array([0, 3, 1, 2])
data = np.array([4, 5, 7, 9])
coo = coo_matrix((data, (row, col)), shape=(4, 4)).toarray()
print(coo)

结果
[[4 0 9 0]
[0 7 0 0]
[0 0 0 0]
[0 0 0 5]]

值得注意的是,COO矩阵可以处理重复坐标,如下例子,(row,col)出现三次(0,0),分别为1,1,1,则(0,0)位置的数值为1+1+1=3

# 对于多个重复坐标,将对应值相加
row = np.array([0, 0, 1, 3, 1, 0, 0])
col = np.array([0, 2, 1, 3, 1, 0, 0])
data = np.array([1, 1, 1, 1, 1, 1, 1])
coo = coo_matrix((data, (row, col)), shape=(4, 4))
print(coo.toarray())

结果
[[3 0 1 0]
[0 2 0 0]
[0 0 0 0]
[0 0 0 1]]

csc_matrix

Compressed Sparse Column matrix
将数据按列压缩,最大的优势是有利于按列切分,适合CSR+CSR以及CSR*CSR的运算
标准的构造方式输入为indptr,indices以及data。
其中列i的行索引存储在indices[indptr[i]:indptr[i+1]]中,其相应值存储在data[indptr[i]:indptr[i+1]]中,如下例子:
列0:对应的indices[0:2]位置的[0,2]行,即(0,0)=1,(2,0)=2
列1:对应的indices[2:3]位置的[2]行,即(2,1)=3
列2:对应的indices[3:6]位置的[0,1,2]行,即(0,2)=4,(1,2)=5,(2,2)=6

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]) # 对应数值
csc = csc_matrix((data, indices, indptr), shape=(3, 3)) #。如果未提供shape参数,则从索引数组推断矩阵维度。
print(csc)
print(csc.toarray())

打印结果
(0, 0) 1
(2, 0) 2
(2, 1) 3
(0, 2) 4
(1, 2) 5
(2, 2) 6

[[1 0 4]
[0 0 5]
[2 3 6]]

csr_matrix

Compressed Sparse Row matrix
同csr的逻辑相同,将数据按行压缩,最大的优势是有利于按行切分,适合CSR+CSR以及CSR*CSR的运算(貌似在乘法运算上快于CSC)
标准的构造方式输入仍为indptr,indices以及data。
其中行i的列索引存储在indices[indptr[i]:indptr[i+1]]中,其相应值存储在data[indptr[i]:indptr[i+1]]中,如下例子:
行0:对应的indices[0:2]位置的[0,2]列,即(0,0)=1,(0,2)=2
行1:对应的indices[2:3]位置的[2]列,即(1,2)=3
行2:对应的indices[3:6]位置的[0,1,2]列,即(2,0)=4,(2,1)=5,(2,2)=6

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])
csr = csr_matrix((data, indices, indptr), shape=(3, 3))
print(csr)
print(csr.toarray())

打印结果
(0, 0) 1
(0, 2) 2
(1, 2) 3
(2, 0) 4
(2, 1) 5
(2, 2) 6

[[1 0 2]
[0 0 3]
[4 5 6]]

发布了22 篇原创文章 · 获赞 0 · 访问量 4428

猜你喜欢

转载自blog.csdn.net/Yolo_C/article/details/104066870