SoFunction
Updated on 2024-11-17

Python Sparse Matrix and Parameter Preservation Code Implementation

1. Sparse matrix creation: coo_matrix()

from  import coo_matrix
# Build sparse matrices
data = [1,2,3,4]
row = [3,6,8,2]
col = [0,7,4,9]
c = coo_matrix((data,(row,col)),shape=(10,10)) #Construct a 10*10 sparse matrix where the values and positions that are not 0 are in the first parameter
print(c)

2. Sparse matrices into dense matrices: todense()

d = ()
print(d)

3. Convert a matrix with many 0-values into a sparse matrix

e = coo_matrix(d) #Convert a matrix with many values of 0 to a sparse matrix
print(e)

4. save: similar to the .mat format in matlab, python can also save the parameter data, in addition to save as csv, json, excel, etc., I personally think that matlab's .mat format is really strong, what can be saved directly ~~~

import numpy as np

# (arg_1,arg_2),arg_1is the filename,arg_2is the array to be saved
aa = (d)
print(aa)
# save
('test_save_1.npy', aa) # Keep an array
('test_save_2', aa=aa, d=d) #Saving multiple arrays,where sparse matrices can be saved directly

5. load: load parameter data

#load
a_ = ('test_save_1.npy')
print(a_)

dt = ('test_save_2.npz') The #npz data is loaded as a dictionary format data
print(dt)
print(dt['aa'])
print(dt['d']) #Get the value of one of the parameters,Similar to the dictionary form of getting

6. Parameter name for getting npz data

# Get the name of the parameter
p_name =list(())
print(p_name)

# Get the value
p_value =list(())
print(p_value)

This is the whole content of this article.