Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

python - how to check if matrix is sparse or not

Tags:

I have a matrix and I want to check if it is sparse or not.

Things I have tried:

  1. isinstance method:

    if isinstance(<matrix>, scipy.sparse.csc.csc_matrix): 

This works fine if I know exactly which sparse class I want to check.

  1. getformat method: But it assumes that my matrix is sparse and give format

But I want a way to know if matrix is sparse or not, and should work irrespective of which sparse class.

Kindly help me.

like image 424
Shweta Avatar asked Mar 08 '16 18:03

Shweta


People also ask

How do you check if a matrix is a sparse matrix?

Calculate the size of the array by multiplying the number of rows with many columns of the array. If the count is greater than size/2, given matrix is the sparse matrix. That means, most of the elements of the array are zeroes. Else, the matrix is not a sparse matrix.

How do you find the sparsity of a matrix?

The number of zero-valued elements divided by the total number of elements (e.g., m × n for an m × n matrix) is called the sparsity of the matrix (which is equal to 1 minus the density of the matrix).

Is sparse a SciPy?

SciPy has a module, scipy. sparse that provides functions to deal with sparse data. There are primarily two types of sparse matrices that we use: CSC - Compressed Sparse Column.

How does Python handle sparse matrix?

Representing a sparse matrix by a 2D array leads to wastage of lots of memory as zeroes in the matrix are of no use in most of the cases. So, instead of storing zeroes with non-zero elements, we only store non-zero elements. This means storing non-zero elements with triples- (Row, Column, value).


2 Answers

scipy.sparse.issparse(my_matrix) 
like image 194
Boa Avatar answered Oct 23 '22 03:10

Boa


You can do sparsity = 1.0 - count_nonzero(X) / X.size

This works for any matrices.

like image 24
Mai N. Avatar answered Oct 23 '22 03:10

Mai N.