To create a sparse matrix with 100 entries you can use the randint
method from numpy random module to generate the indices, then create a coo sparse matrix with 100 random data values at generated indices. After that convert sparse matrix to dense matrix using toarray()
method. To calculate the size of sparse matrix and dense matrix use sys.getsizeof()
method as shown below:
main.py597 chars23 lines
Output:
main.py48 chars3 lines
Note: The size of sparse matrix is much smaller than dense matrix. This is an advantage of using sparse matrices when the majority of the data is zero.
gistlibby LogSnag