Open In App

Python – tensorflow.math.count_nonzero()

Last Updated : 21 Jul, 2021
Improve
Improve
Like Article
Like
Save
Share
Report

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)


Like Article
Suggest improvement
Previous
Next
Share your thoughts in the comments

Similar Reads