In a sparse matrix or sparse array, most of the elements are zero. There is no strict definition regarding the proportion of zero-value elements in a sparse matrix.

numpy sparse matrix

By contrast, if most of the elements are non-zero, the matrix is considered dense. The number of zero-valued elements divided by the total number of elements (e.g., m × n for an m × n matrix) is sometimes referred to as the sparsity of the matrix.

Sparse matrices provide efficient storage of logical data that has a large percentage of zeros. While dense matrices store every single element in memory regardless of value.

sparse matrices store only the nonzero elements and their row indices. For this reason, using sparse matrices can significantly reduce the amount of memory required for data storage.

Sparse matrices are commonly used in machine learning, such as in data that contains counts, data encodings that map categories to counts, and even in whole subfields of machine learning such as natural language processing.

In the previous tutorial, we created SciPy sparse matrix from NumPy, In this tutorial, you will discover how to create a dense matrix from sparse matrices in Python. There are many efficient ways to work with sparse matrices, SciPy provides implementations that you can use directly.

Create Sparse Matrices

SciPy provides tools for creating sparse matrices using multiple data structures, as well as tools for converting a dense matrix to a sparse matrix.

NumPy arrays can transparently operate on SciPy sparse arrays. NumPy data structures can also operate transparently on SciPy sparse arrays. A dense matrix stored in a NumPy array can be converted into a SciPy sparse matrix. Create sparse matrix using the CSR representation by calling the csr_matrix() function.

import numpy as np
from scipy import sparse

a1 = np.array([[1, 0, 0, 62, 0, 0], 
               [0, 0, 12, 0, 0, 0], 
               [0, 0, 0, 4, 0, 0]])

s1 = sparse.csr_matrix(a1)
Sparse Matrix SciPy

the toarray() method will convert the sparse matrix to numpy array.

Sparse Matrix to Dense Matrix

To convert SciPy sparse matrix to dense matrix, youcan use todense() method.

SciPy create dense matrix

Related Post