Saturday, November 15, 2025
HomeLanguagesPython – tensorflow.math.count_nonzero()

Python – tensorflow.math.count_nonzero()

TensorFlow is open-source Python library designed by Google to develop Machine Learning models and deep learning  neural networks. 

count_nonzero() is used to count the number of non zero elements in a Tensor.

Syntax: tf.math.count_nonzero(  input, axis, keepdim, dtype, name)

Parameters: 

  • input: It’s a Tensor that need to be reduced.
  • axis(optional): It defines the axis along which input need to be reduced. Allowed range for this is  [-rank(input), rank(input)). If no value is given then default is none i.e. input will be reduced along all axis.
  • keepdim(optional): If it is true, it will retain the reduced dimensions with length 1.
  • dtype(optional): It defines the output dtype. Default if int32.
  • name(optional): It defines the name for the operation.

Returns: 

It returns a tensor that contains the number of non-zero values.

Example 1:

Python3




# importing the library
import tensorflow as tf
 
# initializing the input
a = tf.constant([1,0,2,5,0], dtype = tf.int32)  # 3 non-zero
 
# Printing the input
print("Input: ",a)
 
# Counting non-zero
res  = tf.math.count_nonzero(a)
 
# Printing the result
print("No of non-zero elements: ",res)


Output:

Input:  tf.Tensor([1 0 2 5 0], shape=(5,), dtype=int32)
No of non-zero elements:  tf.Tensor(3, shape=(), dtype=int64)

Example 2: When input tensor is of type string, “” is considered as empty string. ” ” is non zero.

Python3




# importing the library
import tensorflow as tf
 
# initializing the input
a = tf.constant([""," ","a","b"])  # 3 non-zero
 
# Printing the input
print("Input: ",a)
 
# Counting non-zero
res  = tf.math.count_nonzero(a)
 
# Printing the result
print("No of non-zero elements: ",res)


Output:

Input:  tf.Tensor([b'' b' ' b'a' b'b'], shape=(4,), dtype=string)
No of non-zero elements:  tf.Tensor(3, shape=(), dtype=int64)
Dominic
Dominichttp://wardslaus.com
infosec,malicious & dos attacks generator, boot rom exploit philanthropist , wild hacker , game developer,
RELATED ARTICLES

Most Popular

Dominic
32399 POSTS0 COMMENTS
Milvus
95 POSTS0 COMMENTS
Nango Kala
6765 POSTS0 COMMENTS
Nicole Veronica
11917 POSTS0 COMMENTS
Nokonwaba Nkukhwana
11984 POSTS0 COMMENTS
Shaida Kate Naidoo
6890 POSTS0 COMMENTS
Ted Musemwa
7143 POSTS0 COMMENTS
Thapelo Manthata
6838 POSTS0 COMMENTS
Umr Jansen
6840 POSTS0 COMMENTS