當前位置: 首頁>>編程示例 >>用法及示例精選 >>正文


Python tensorflow.math.count_nonzero()用法及代碼示例

TensorFlow是Google設計的開源Python庫,用於開發機器學習模型和深度學習神經網絡。

count_nonzero()用於計算張量中非零元素的數量。

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

參數:

  • input:需要減少張量。
  • axis(optional):它定義了需要減少輸入的軸。允許的範圍是[-rank(輸入),rank(輸入))。如果未指定任何值,則默認為無,即輸入將沿所有軸減少。
  • keepdim(optional):如果為true,則將保留長度為1的縮小尺寸。
  • dtype(optional):它定義了輸出dtype。如果為int32,則為默認值。
  • name(optional):它定義了操作的名稱。

返回值:



它返回一個包含非零值數量的張量。

範例1:

Python3

# imporing 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)

輸出:

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

# imporing 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)



相關用法


注:本文由純淨天空篩選整理自aman neekhara大神的英文原創作品 Python – tensorflow.math.count_nonzero()。非經特殊聲明,原始代碼版權歸原作者所有,本譯文未經允許或授權,請勿轉載或複製。