How to check if a nd array is non zero?

I have a nd array. How could I check if the nd array is non-zeros for all elements in the array? For example, the nd array size of 20x20. It will return True if has all elements in the nd array are zeros, otherwise return False.


Would something like this work for you? These lines of code will check if an nd array is non-zero for all elements in it:

import mxnet as mx
a = mx.ndarray.random_randint(low=0, high=5, shape=(20,20))
print(a)   # just to make sure there is at least a zero in the array
if mx.nd.sum(a == 0) > 0: print('Found zero elements in the array')

If you don’t worry about performance, here is a quick workaround

print(not mx.nd.not_equal(a, mx.nd.zeros(a.shape, ctx=a.context)).sum())

where a is your ndarray.

1 Like

Thanks all. How can I check if all elements of the nd array are one or zeros, instead of count number of non zeros. For example

import mxnet as mx
import numpy as np
a = mx.ndarray.zeros((1,1,112,112), dtype=np.float32)
b = mx.ndarray.ones((1,1,112,112), dtype=np.float32)
# Output 
a is zero metric :True
b is not zero metric: False

This line:

if mx.nd.sum(a == 0) > 0

does not count the number of non zeros, but it actually provides a True or False value if any zero-element in the array is found.

1 Like