📜  Python – tensorflow.math.count_nonzero()

📅  最后修改于: 2022-05-13 01:55:07.994000             🧑  作者: Mango

Python – tensorflow.math.count_nonzero()

TensorFlow 是由 Google 设计的开源Python库,用于开发机器学习模型和深度学习神经网络。

count_nonzero()用于计算张量中非零元素的数量。

示例 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)