9、张量的排序
- sort/argsort
- topk
- top-5 Acc
1、sort,argsort
sort:对序列进行一个完全的排序
argsort:返回排序后的index
(1)tf.random.shuffle(),沿着张量的第一个维度进行打乱
1 a = tf.range(5) 2 b = tf.random.shuffle(a) 3 print(b.numpy()) # [3 4 1 2 0] 4 5 a = tf.constant([[1,2],[2,3],[5,6]]) 6 b = tf.random.shuffle(a) 7 print(b.numpy()) #只打乱了第一个维度,里面的维度没有打乱
""" [[5 6] [1 2] [2 3]] """
(2)sort和argsort
①一维张量
1 a = tf.random.shuffle(tf.range(8)) 2 print(a) #tf.Tensor([1 2 0 4 3], shape=(5,), dtype=int32) 3 4 b1 = tf.sort(a) #默认是升序 5 print(b1) #tf.Tensor([0 1 2 3 4], shape=(5,), dtype=int32) 6 b2 = tf.sort(a,direction='DESCENDING') # descending:下降的 7 print(b2) #tf.Tensor([4 3 2 1 0], shape=(5,), dtype=int32) 8 9 indx = tf.argsort(a,direction='DESCENDING') 10 print(indx) #tf.Tensor([3 7 0 6 4 1 2 5], shape=(8,), dtype=int32),得到降序排列后的索引值 11 b3 = tf.gather(a,indx) 12 print(b3) #tf.Tensor([7 6 5 4 3 2 1 0], shape=(8,), dtype=int32),通过索引index在a中收集对应的值,得到降序后的排列
②多维张量
1 a = tf.random.uniform([3,3],maxval=10,dtype=tf.int32) 2 print(a.numpy()) """ [[2 3 4] [8 8 9] [3 1 5]] """ 3 b1 = tf.sort(a) #对每一行进行升序排序 4 print(b1.numpy()) """ [[2 3 4] [8 8 9] [1 3 5]] """ 5 b2 = tf.sort(a,direction='DESCENDING') 6 print(b2.numpy()) """ [[4 3 2] [9 8 8] [5 3 1]] """ 7 b3 = tf.argsort(a) #默认是升序 8 print(b3.numpy()) """ [[0 1 2] [0 1 2] [1 0 2]] """
2、topk,tf.math.top_k(a,k),返回values和indices两个张量
tf.sort对张量的某一个维度进行完全的排序,有可能会耗费一定的时间,在某些情况下我们不需要对所有的张量进行排序,只希望得到最大值或者最小值或者最大的和最小的两个值,top-k可以得到最大的或者最小的前k个值
1 # top_k 2 a = tf.random.uniform([3,3],maxval=10,dtype=tf.int32) 3 print(a.numpy()) 4 5 res = tf.math.top_k(a,2) 6 print(res) 7 print(res.values.numpy()) 8 print(res.indices.numpy())
输出:对每一行进行排序,然后输出前两个最大的值
[[8 6 9] [5 9 7] [8 7 6]] TopKV2(values=<tf.Tensor: id=5, shape=(3, 2), dtype=int32, numpy= array([[9, 8], [9, 7], [8, 7]])>, indices=<tf.Tensor: id=6, shape=(3, 2), dtype=int32, numpy= array([[2, 0], [1, 2], [0, 1]])>) [[9 8] [9 7] [8 7]]
[[2 0] #每一行中的索引值 [1 2] [0 1]]
3、top_k accuracy
top_1的条件是最严苛的,只有当第一个预测的和label相同才可以,而top_k(k>1)只要前k个预测中有一个预测正确就算预测正确,top_5是imageNet中反应模型好坏的一个重要的指标