Friday, July 24, 2026
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

2 COMMENTS

Most Popular

Dominic
32520 POSTS0 COMMENTS
Milvus
131 POSTS0 COMMENTS
Nango Kala
6902 POSTS0 COMMENTS
Nicole Veronica
12017 POSTS0 COMMENTS
Nokonwaba Nkukhwana
12115 POSTS0 COMMENTS
Shaida Kate Naidoo
7023 POSTS0 COMMENTS
Ted Musemwa
7265 POSTS0 COMMENTS
Thapelo Manthata
6980 POSTS0 COMMENTS
Umr Jansen
6971 POSTS0 COMMENTS