This article takes Csr_matrix as an example to illustrate the use of the sparse matrix, other types of sparse matrices can be referenced https://docs.scipy.org/doc/scipy/reference/sparse.html
Csr_matrix is an abbreviated combination of the compressed Sparse Row matrix, which describes two of its initialization methods
Csr_matrix (data, (Row_ind, Col_ind)), [Shape= (M, N)])
Where data, row_ind and col_ind satisfy the relationship A[row_ind[k], Col_ind[k]] c10>= data[k].
Csr_matrix (data, indices, indptr), [Shape= (M, N)])
is the standard CSR representation where the column indices for row i am stored in indices[indptr[i]:indptr[i+1]] and their corresponding values is stored in data[indptr[i]:indptr[i+1]]. If The shape parameter is not supplied, the matrix dimensions was inferred from the index arrays.
The official documents above give the following: The parameters of sparse matrices and their meanings, and how to construct sparse matrices. The presentation is simple and clear and pleasing to read.
Sparse matrices can be used in arithmetic operations:they support addition, subtraction, multiplication, division, and MA Trix Power
Advantages of the CSR format
- Efficient arithmetic operations CSR + CSR, CSR * CSR, etc.
- Efficient row Slicing
- Fast matrix vector Products
Disadvantages of the CSR format
- Slow column slicing operations (consider CSC)
- Changes to the sparsity structure is expensive (consider LIL or DOK)
Some of the features of the sparse matrix and the pros and cons of Csr_matrix in the official documents above, and the technical implementations that can be considered while pointing out various drawbacks.
code Example 1
Import NumPy as Npfrom scipy.sparse import csr_matrixrow = Np.array ([0, 0, 1, 2, 2, 2]) col = Np.array ([0, 2, 2, 0, 1, 2]) d ATA = Np.array ([1, 2, 3, 4, 5, 6]) A = Csr_matrix (data, (row, col)), Shape= (3, 3)). ToArray ()
Print (a)
Operation Result:
Array ([[1, 0, 2], [0, 0, 3], [4, 5, 6]])
code Example 2
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]) a = Csr_matrix (da TA, indices, indptr), Shape= (3, 3)). ToArray () print (a)
Allowed results:
Array ([[1, 0, 2], [0, 0, 3], [4, 5, 6]])
How to use the Python scipy.sparse matrix