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


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

TensorFlow是Google設計的開源python庫,用於開發機器學習模型和深度學習神經網絡。 Tensorflow具有方法argsort(),該方法用於按排序順序查找Tensor的索引。

用法:tf.argsort(values, axis, direction, stable, name)

參數:

  • values:它是任何尺寸的數字張量。
  • axis:它定義了需要進行短路的軸。如果未指定任何值,則默認值為-1,並基於最後一個軸進行排序。
  • direction:升序或降序。
  • stable:是非題。如果是真的,則在相等的情況下會保持原始順序。
  • name:這是一個可選參數,用於定義操作的名稱。

返回:它返回一個int32類型的張量,其形狀與值相同。該張量包含索引,這些索引將給出給定值的排序順序。

如果軸或方向無效,則會引發ValueError。

範例1:



Python3

# importing the library 
import tensorflow 
  
# initializing value 
a= [1,5,2.5,10,7,8.5] 
  
# getting the indices for sorted values 
b = tensorflow.argsort(a,axis=-1,direction='ASCENDING',stable=False) 
  
# printing the result 
print('Indices:'b) 
  
print('Sorted values') 
#printing the sorted value 
for i in b:
  print(a[i])

輸出:

Indices:tf.Tensor([0 2 1 4 5 3], shape=(6,), dtype=int32)
Sorted Values
1
2.5
5
7
8.5
10

範例2:在此示例中,錯誤的值傳遞給了方向。這將引發ValueError。

Python3

# importing the library 
import tensorflow 
  
# initializing value 
a= [1,5,2.5,10,7,8.5] 
  
# getting the indices for sorted values 
b = tensorflow.argsort(a,axis=-1,direction='ASC',stable=False)

輸出:

ValueError:ASC should be one of ASCENDING, DESCENDING





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