Python – tensorflow.math.count_nonzero()
TensorFlow 是由 Google 设计的开源Python库,用于开发机器学习模型和深度学习神经网络。
count_nonzero()用于计算张量中非零元素的数量。
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.
示例 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)
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)
输出:
Input: tf.Tensor([1 0 2 5 0], shape=(5,), dtype=int32)
No of non-zero elements: tf.Tensor(3, shape=(), dtype=int64)
示例 2:当输入张量为字符串类型时, “”被视为空字符串。 ” ”非零。
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)
输出:
Input: tf.Tensor([b'' b' ' b'a' b'b'], shape=(4,), dtype=string)
No of non-zero elements: tf.Tensor(3, shape=(), dtype=int64)