tensor排序
Tensorflow有两个排序功能,一个是元素排序,一个是元素排序索引。
tf.sort()元素排序得到排序结果
功能是默认输出tensor从小到大排序后的结果
tf.sort(
values, axis=-1, direction='ASCENDING', name=None
)
direction='DESCENDING’为降序排序
tf.argsort()元素排序得到索引
功能是返回元素的排序索引。比如通过tf.argsort计算向量a从小到大的排序索引A,则A[i]=n表示第i小的元素是n。
tf.argsort(
values, axis=-1, direction='ASCENDING', stable=False, name=None
)
同样将direction='DESCENDING’为降序排序
两次tf.argsort()得到当前元素排第几
即
index=tf.argsort(values,axis=-1,direction='ASCENDING')
now_rank = tf.argsort(index,axis=-1,direction='ASCENDING')
下面用代码展示一下上面三种情形:
import tensorflow as tf
X=tf.random.normal(shape=(1,20))
print(X)
X_sort = tf.sort(X, axis=1, direction='DESCENDING')
# 按元素大小输出
print(X_sort)
index = tf.argsort(X, axis=1, direction='DESCENDING')
now_rank = tf.argsort(index)
# 输出最大到最小的value索引
print(index)
# 输出两次argsort结果
print(now_rank)