Python – tensorflow.argsort() 方法
TensorFlow 是由 Google 设计的开源Python库,用于开发机器学习模型和深度学习神经网络。 Tensorflow 有一个方法 argsort() 用于按排序顺序查找张量的索引。
Syntax: tf.argsort(values, axis, direction, stable, name)
Parameters:
- values: It is a numeric Tensor of any dimension.
- axis: It defines the axis along which shorting need to be done. If no value is given, default is -1 and sorting is done based on last axis.
- direction: Either ASCENDING or DESCENDING.
- stable: Either True or False. If it’s true then in case of equality original order is maintained.
- name: It’s an optional argument which define the name for the operation.
Return: It returns a Tensor of type int32 having same shape as values.This tensor contains the indices that will give the sorted order of given values.
If axis or direction is invalid it will raise 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])
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)
输出:
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