Sort/argsort
Sort : 对某一维度上的完全排序,返回一个排序后的 tensor argsort :对某一维度上的完全排序,返回一个排序后tensor所对应的位置(索引) 参数: direction:降序DESCENDING、升序ASCENDING axis : 维度
a = tf.random.shuffle(tf.range(5))
print(a)
print(tf.sort(a, direction='DESCENDING'))
print(tf.argsort(a, direction='DESCENDING'))
idx = tf.argsort(a,direction='DESCENDING')
print(tf.gather(a, idx))
a = tf.random.uniform([3,3],maxval=10,dtype=tf.int32)
print(a)
print(tf.sort(a))
print(tf.sort(a,axis=0))
print((tf.argsort(a)))
tf.math.top_k()
tf.math.top_k() 参数:input, k=1, sorted=True, name=None k 代表前k个,True表示正序
返回值为两个序列,一个values,对应排序后的前k个数的值;一个indices,对应排序后前k个数对应的索引
a = tf.random.uniform([3,8],maxval=10,dtype=tf.int32)
print(a)
res = tf.math.top_k(a,k=2)
print(res)
'''注意:a的值每次运行是不一样的
TopKV2(values=<tf.Tensor: shape=(3, 2), dtype=int32, numpy=
array([[9, 9],
[9, 8],
[5, 4]])>, indices=<tf.Tensor: shape=(3, 2), dtype=int32, numpy=
array([[3, 5],
[3, 6],
[6, 1]])>)
'''
print(res.indices)
print(res.values)
top-k accuracy:
???
prob = tf.constant([[0.1,0.2,0.7],[0.2,0.7,0.1]])
target = tf.constant([2,0])
k_b = tf.math.top_k(prob,3).indices
print(k_b)
k_b = tf.transpose(k_b,[1,0])
print(k_b)
target = tf.broadcast_to(target,[3,2])
print(target)
def accuracy(output,target,topk=(1,)) :
maxk = max(topk)
batch_size = target.shape[0]
pred = tf.math.top_k(output,maxk).indices
pred = tf.transpose(pred,perm=[1,0])
target_ = tf.broadcast_to(target,pred.shape)
correct = tf.equal(pred,target_)
res = []
for k in topk:
correct_k = tf.cast(tf.reshape(correct[:k],[-1]),dtype=tf.float32)
correct_k = tf.reduce_sum(correct_k)
acc = float(correct_k / batch_size)
res.append(acc)
return res
|