Wu Yuxiong - born naturally TensorFlow2 Tutorial: Sort tensor

import tensorflow as tf

a = tf.random.shuffle(tf.range(5))
a
tf.sort(a, direction='DESCENDING')
# Returns the index 
tf.argsort (A, direction = ' DESCENDING ' )
idx = tf.argsort(a, direction='DESCENDING')
tf.gather(a, idx)
idx = tf.argsort(a, direction='DESCENDING')
tf.gather(a, idx)
a = tf.random.uniform([3, 3], maxval=10, dtype=tf.int32)
a
tf.sort(a)
tf.sort(a, direction='DESCENDING')
idx = tf.argsort(a)
idx
# Return to the previous two values 
RES = tf.math.top_k (A, 2 )
res
res.values
res.indices
prob = tf.constant([[0.1, 0.2, 0.7], [0.2, 0.7, 0.1]])
target = tf.constant([2, 0])
# Probability largest index on top 
K_b = tf.math.top_k (Prob, 3 ) .indices
k_b
k_b = tf.transpose(k_b, [1, 0])
k_b
# Real value broadcast, and prod comparison 
target = tf.broadcast_to (target, [. 3, 2 ])
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
# 10 samples 6 class 
Output = tf.random.normal ([10, 6 ])
 # so that the combined probability of all samples. 1 
Output = tf.math.softmax (Output, Axis =. 1 )
 # 10 corresponding to the sample labeled 
target tf.random.uniform = ([10], = MAXVAL. 6, DTYPE = tf.int32)
 Print (F ' Prob: output.numpy {()} ' )
pred = tf.argmax(output, axis=1)
print(f'pred: {pred.numpy()}')
print(f'label: {target.numpy()}')

acc = accuracy(output, target, topk=(1, 2, 3, 4, 5, 6))
print(f'top-1-6 acc: {acc}')

 

Guess you like

Origin www.cnblogs.com/tszr/p/12133374.html