Tensorflow(十) —— Tensor的排序
1. 主要方法
- 1、sort / argsort
- 2、top_k :tf.math.top_k
- 3、top5 用于ACC
2. sort与argsort
import numpy as np
import pandas as pd
import tensorflow as tf
# **************** sort argsort
# 1维
print("*"*8,"一维","*"*8)
a = tf.random.shuffle(tf.range(10))
print("a:",a)
b = tf.sort(a,direction = "DESCENDING")
b1 = tf.argsort(a,direction="DESCENDING")
print("b:",b)
print("b1:",b1)
c = tf.sort(a,direction="ASCENDING")
c1 = tf.argsort(a,direction="ASCENDING")
print("c:",c)
print("c1:",c1)
b2 = tf.gather(a,b1)
c2 = tf.gather(a,c1)
print("b2:",b2)
print("c2:",c2)
# 高维
d = tf.random.uniform([3,4],maxval = 100,minval=10,dtype=tf.int32)
print("d:",d)
d1 = tf.sort(d) # 默认对最后一个维度进行ASCENDING
print("d1:",d1)
d2 = tf.argsort(d,axis = 0,direction = "DESCENDING") # 可通过axis轴调整排序依据的轴
print("d2:",d2)
3. top_k
only return top_k values and indices
# *************** top_k
"""
only return top_k values and indices
"""
a = tf.random.normal([4,3],mean = 50, stddev=16)
a = tf.cast(a,dtype=tf.int32)
print("a:",a)
result = tf.math.top_k(a,2) # 默认为取出按最后个轴排序的前k个值和索引
print("result:",result) # 返回结果为元组
print(result.indices)
print(result.values)
4. Top_k用于Accuracy
"""
prob = [0.1 0.2 0.3 0.4]
label = [2]
only consider top_1 prediction: [3] 0%
only consider top_2 prediction [3 2] 100%
only consider top_3 prediction [3 2 1] 100%
"""
# 实例 计算top_k的accuracy
prob = tf.convert_to_tensor([[0.1,0.2,0.7],[0.2,0.7,0.1]])
target = tf.constant([2,0])
predict = tf.math.top_k(prob,k = 3).indices # 取出排名前三的概率值的编号
print("predict",predict.numpy())
predict = tf.transpose(predict,[1,0]) # 每列代表一条预测结果
print("predict:",predict.numpy())
target = tf.broadcast_to(target,[3,2])
print("target:",target.numpy())
5. top_k 用于accuracy 的完整案例
def topk_accuracy(output,target,topk = (1,)):
"""
output:[b,n] b条数据的n个概率值
target:[b] b条数据的b个真实值
topk:元组 可计算多个topk的准确值
"""
output = tf.constant(output)
target = tf.constant(target)
output_ = tf.transpose(tf.math.top_k(output,k = max(topk)).indices,[1,0])
target_ = tf.broadcast_to(target,output_.shape)
compare = tf.equal(target_,output_)
result = []
for k in topk:
acc = tf.reduce_sum(tf.cast(compare[:k,:],dtype=tf.float32))/output.shape[0]
result.append(float(acc))
return result
output = tf.math.softmax(tf.random.normal([100,10]))
# print("output:",output.numpy())
target = tf.random.uniform([100],maxval=10,minval=0,dtype=tf.int32)
print("target:",target)
acc = topk_accuracy(output,target,[1,2,3,4,5,6,7,8,9,10])
print("Accuracy:",acc)
本文为参考龙龙老师的“深度学习与TensorFlow 2入门实战“课程书写的学习笔记
by CyrusMay 2022 04 16