使用python进行稀疏矩阵的csr压缩
import numpy as np
import scipy.sparse as sp
def CSR(x):
w=len(x[0])
h=len(x)
A = np.array(x)
AS = sp.csr_matrix(A)
print("data=",AS.data)
print("indptr=",AS.indptr)
print("indices=",AS.indices)
print("compress_rate=",(len(AS.data)+len(AS.indptr)+len(AS.indices))/(w*h))
def generate_matrix(x,r,s):
matrix=[[0]*x]*x
matrix_r=np.random.randint(0,100,(r,x))
matrix_r=matrix_r.tolist()
for i in range(len(matrix_r)):
for j in range(len(matrix_r[0])):
if(matrix_r[i][j]<100*s):
matrix_r[i][j]=0
for k in range(x):
if(k<r):
matrix[k]=matrix_r[k]
else:
matrix[k]=matrix[k-r]
return matrix
a=generate_matrix(6,6,0.8)
for i in a:
print(i)
CSR(a)
[90, 0, 0, 0, 84, 97]
[0, 0, 0, 0, 0, 0]
[0, 0, 0, 0, 87, 0]
[0, 0, 89, 0, 80, 0]
[97, 80, 0, 0, 89, 0]
[0, 0, 0, 0, 0, 0]
data= [90 84 97 87 89 80 97 80 89]
indptr= [0 3 3 4 6 9 9]
indices= [0 4 5 4 2 4 0 1 4]
compress_rate= 0.6944444444444444