PHPFixing
  • Privacy Policy
  • TOS
  • Ask Question
  • Contact Us
  • Home
  • PHP
  • Programming
  • SQL Injection
  • Web3.0

Friday, October 28, 2022

[FIXED] How to check if a SciPy CSR matrix is empty (i.e. contains only zeroes)?

 October 28, 2022     is-empty, python, scipy, sparse-matrix     No comments   

Issue

What is the canonical way to check if a SciPy CSR matrix is empty (i.e. contains only zeroes)?

I use nonzero():

def is_csr_matrix_only_zeroes(my_csr_matrix):
    return(len(my_csr_matrix.nonzero()[0]) == 0)

from scipy.sparse import csr_matrix
print(is_csr_matrix_only_zeroes(csr_matrix([[1,2,0],[0,0,3],[4,0,5]])))
print(is_csr_matrix_only_zeroes(csr_matrix([[0,0,0],[0,0,0],[0,0,0]])))
print(is_csr_matrix_only_zeroes(csr_matrix((2,3))))
print(is_csr_matrix_only_zeroes(csr_matrix([[0,0,0],[0,1,0],[0,0,0]])))

outputs

False
True
True
False

but I wonder whether there exist more direct or efficient ways.

(Related but different: Check if scipy sparse matrix entry exists)


Solution

my_csr_matrix.nnz == 0

The nnz attribute records the Number of NonZero entries... unless your CSR matrix is in a weird, nonnormalized form, for example if it has duplicate entries or explicitly stored zeros.

If you have to deal with duplicate entries or explicit zeros, you can use the much more expensive csr_matrix.count_nonzero method:

my_csr_matrix.count_nonzero() == 0


Answered By - user2357112
Answer Checked By - Clifford M. (PHPFixing Volunteer)
  • Share This:  
  •  Facebook
  •  Twitter
  •  Stumble
  •  Digg
Newer Post Older Post Home

0 Comments:

Post a Comment

Note: Only a member of this blog may post a comment.

Total Pageviews

Featured Post

Why Learn PHP Programming

Why Learn PHP Programming A widely-used open source scripting language PHP is one of the most popular programming languages in the world. It...

Subscribe To

Posts
Atom
Posts
Comments
Atom
Comments

Copyright © PHPFixing