using python and numpy create a sparse matrix 100x100 with 100 entries create a dense matrix 100x100 with 100 entries use sys.getsizeof to determine the sizes in python

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.py
import numpy as np
import sys

# create a sparse matrix
sparse_matrix = np.zeros((100, 100))
indices = np.random.randint(0, 100, (100, 2))
data = np.random.rand(100)
for i in range(100):
    sparse_matrix[indices[i,0], indices[i,1]] = data[i]
sparse_matrix = sparse_matrix.tocoo()

# Calculate size of sparse matrix
sparse_size = sys.getsizeof(sparse_matrix)

# Convert sparse matrix to dense matrix
dense_matrix = sparse_matrix.toarray()

# Calculate size of dense matrix
dense_size = sys.getsizeof(dense_matrix)

print("Sparse Matrix size:", sparse_size)
print("Dense Matrix size:", dense_size)
597 chars
23 lines

Output:

main.py
Sparse Matrix size: 56
Dense Matrix size: 80968
48 chars
3 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.

related categories

gistlibby LogSnag