SciPy – Sparse Matrix Multiplication
Sparse matrices are those matrices that have the most of their elements as zeroes. scipy.sparse is SciPy 2-D sparse matrix package for numeric data. It provides us different classes to create sparse matrices. csc_matrix and csr_matrix are the two such classes. csc_matrix() is used to create a compressed sparse column matrix whereas csr_matrix() is used to create a compressed sparse row matrix.
Note: For more information about how to create a sparse matrix please visit How to Create a Sparse Matrix in Python
Attention geek! Strengthen your foundations with the Python Programming Foundation Course and learn the basics.
To begin with, your interview preparations Enhance your Data Structures concepts with the Python DS Course. And to begin with your Machine Learning Journey, join the Machine Learning - Basic Level Course
We use the multiply() method provided in both csc_matrix and csr_matrix classes to multiply two sparse matrices. We can multiply two matrices of same format( both matrices are csc or csr format) and also of different formats ( one matrix is csc and other is csr format).
Example 1: Multiply two csc matrices
We create two sparse matrices of compressed sparse column format using csc_matrix() and multiply them using multiply() method.
Example 2. Multiply two csr matrices
We create two sparse matrices of compressed sparse row format using csr_matrix() and multiply them using multiply() method.
Example 3. Multiply csc and csr matrices
We create two sparse matrices, one of compressed sparse column format and other of compressed sparse row format. Multiply them using multiply() method.