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


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

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

gather()用於根據提供的索引對輸入張量進行切片。

用法:tensorflow.gather( params, indices, validate_indices, axis, batch_dims, name)

參數:

  • params:它是張量,等級大於或等於軸+1。
  • indices:它是dtype int32或int64的張量。該值應在[0,params.shape [axis])範圍內。
  • axis:它是dtype int32或int64的張量。它定義了應該從中收集索引的軸。默認值為0,並且必須大於等於batch_dims。
  • batch_dims:它是一個整數,代表編號或批次尺寸。它必須小於或等於等級( index )。
  • name:它定義了操作的名稱。

返回值:



它返回一個與param具有相同dtype的Tensor。

範例1:

Python3

# Importing the library 
import tensorflow as tf 
  
# Initializing the input 
data = tf.constant([1, 2, 3, 4, 5, 6]) 
indices = tf.constant([0, 1, 2, 1]) 
  
# Printing the input 
print('data:',data) 
print('indices:',indices) 
  
# Calculating result 
res = tf.gather(data, indices) 
  
# Printing the result 
print('res:',res)

輸出:

data: tf.Tensor([1 2 3 4 5 6], shape=(6,), dtype=int32)
indices: tf.Tensor([0 1 2 1], shape=(4,), dtype=int32)
res: tf.Tensor([1 2 3 2], shape=(4,), dtype=int32)

範例2:

Python3

# Importing the library 
import tensorflow as tf 
  
# Initializing the input 
data = tf.constant([[1, 2], [3, 4], [5, 6]]) 
indices = tf.constant([2, 0, 1]) 
  
# Printing the input 
print('data:',data) 
print('indices:',indices) 
  
# Calculating result 
res = tf.gather(data, indices) 
  
# Printing the result 
print('res:',res)

輸出:

data: tf.Tensor(
[[1 2]
 [3 4]
 [5 6]], shape=(3, 2), dtype=int32)
indices: tf.Tensor([2 0 1], shape=(3,), dtype=int32)
res: tf.Tensor(
[[5 6]
 [1 2]
 [3 4]], shape=(3, 2), dtype=int32)





相關用法


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