How do you convert a matrix to a sparse matrix in python?
In Python, the Scipy library can be used to convert the 2-D NumPy matrix into a Sparse matrix. SciPy 2-D sparse matrix package for numeric data is scipy.sparse Show
The scipy.sparse package provides different Classes to create the following types of Sparse matrices from the 2-dimensional matrix:
CSR (Compressed Sparse Row) or CSC (Compressed Sparse Column) formats support efficient access and matrix operations. Example code to Convert Numpy matrix into Compressed Sparse Column(CSC) matrix & Compressed Sparse Row (CSR) matrix using Scipy classes:
create a 2-D Numpy matrix
Print the matrix & other details:
Converting Matrix A to the Compressed sparse row matrix representation using csr_matrix Class:
The output of print statements:
Converting Matrix A to Compressed Sparse Column matrix representation using csc_matrix Class:
The output of print statements:
As it can be seen the size of the compressed matrices is 56 bytes and the original matrix size is 184 bytes. For a more detailed explanation and code examples please refer to this article: https://limitlessdatascience.wordpress.com/2020/11/26/sparse-matrix-in-machine-learning/ In this article, we will step by step procedure to convert a regular matrix into a sparse matrix easily using Python. Photo by Marco Pregnolato on UnsplashIntroductionMatrix is a type of data structure similar to an array where values are stored in rows and columns. Here, the values are of a unique type. When dealing with matrices (linear algebra) in Machine Learning and NLP, we often hear about two types of matrices as -
Note — There are no criteria as such how many zero values in a matrix determine that there is a need to sparse the matrix. Algorithm ExplanationImagine you have a large matrix with The simple method here is to neglect all Approach:
Visual ExplanationLet’s say we are given a matrix that has most of the elements to be The following Time to CodeIn this section, we will try to code this in two different ways. One, with the help of the Let’s get started … Necessary Imports import numpy as np Random Matrix Creation Just for the demonstration, we will make sure that the matrix contains >>> mat = np.random.randint(low=0, high=3, size=(5, 5)) SCIPY ImplementationWith the help of the method, >>> smat = csr_matrix(mat) We can think of a Custom ImplementationIn order to implement it from scratch, we can follow the Algorithmic approach that I have explained previously. class SparseMatrix(): The above class Object Creation sparse = SparseMatrix(arr=mat) Output — List >>> smat_c = sparse.retain_sparsity() Output — dictionary >>> smat_d = sparse.retain_sparsity(to_dict=True) Conclusion
>>> from sys import getsizeof
Buy Me Coffee If you have liked my article you can buy some coffee and support me here. That would motivate me to write and learn more about what I know. How do you convert a matrix into a sparse matrix in python?Approach:. Create an empty list which will represent the sparse matrix list.. Iterate through the 2D matrix to find non zero elements.. If an element is non zero, create a temporary empty list.. Append the row value, column value, and the non zero element itself into the temporary list.. How do you convert a matrix to a sparse matrix?Approach:. Get the matrix with most of its elements as 0.. Create a new 2D array to store the Sparse Matrix of only 3 columns (Row, Column, Value).. Iterate through the Matrix, and check if an element is non zero. ... . After each insertion, increment the value of variable length(here 'len').. How do you find a sparse matrix in python?To check whether a matrix is a sparse matrix, we only need to check the total number of elements that are equal to zero. If this count is more than (m * n)/2, we return true.
How do you create an empty sparse matrix in python?to construct an empty matrix with shape (M, N) dtype is optional, defaulting to dtype='d'. 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]] = data[k] .
|