How to generate a dense matrix from a sparse matrix in NumPy?

Learn, how to generate a dense matrix from a sparse matrix in NumPy?
By Pranit Sharma Last updated : December 21, 2023

NumPy is an abbreviated form of Numerical Python. It is used for different types of scientific operations in python. Numpy is a vast library in python which is used for almost every kind of scientific or mathematical operation. It is itself an array which is a collection of various methods and functions for processing the arrays.

Problem statement

Suppose that we are given a sparse matrix and we need to create a dense matrix from this sparse matrix using numpy.

Generating a dense matrix from a sparse matrix in NumPy

For this purpose, we will use todense() on our sparse matrix which will directly convert it into a dense matrix.

This method returns a dense matrix representation of this matrix.

A NumPy matrix object with the same shape and containing the same data represented by the sparse matrix, with the requested memory order. If out (parameter) was passed and was an array (rather than a numpy.matrix()), it will be filled with the appropriate values and returned wrapped in a numpy.matrix() object that shares the same memory.

Let us understand with the help of an example,

Python code to generate a dense matrix from a sparse matrix in NumPy

# Import numpy
import numpy as np

from scipy.sparse import csr_matrix

# Creating a sparse matrix
A = csr_matrix([[1,0,2],[0,3,0]])

# Display original matrix
print("Original Matrix:\n",A,"\n")

# Converting sparse matrix to dense matrix
res = A.todense()

# Display result
print("Result:\n",res)

Output

Example: How to generate a dense matrix from a sparse matrix in NumPy?

Python NumPy Programs »

Comments and Discussions!

Load comments ↻





Copyright © 2024 www.includehelp.com. All rights reserved.