import tensorflow as tf
import numpy as np
print(tf.__version__)
1.数组排序
tf.sort tf.argsort
arry = tf.random.shuffle(tf.range(0, 5))
print(ary)
arry_sort = tf.sort(arry, direction="DESCENDING")
print(arry_sort)
arry_argsort = tf.argsort(arry, direction="DESCENDING")
print(arry_argsort)
print(tf.gather(arry, arry_argsort))
arry = tf.random.uniform((3, 3), maxval= 10, dtype=tf.int32)
print(arry)
arry_sort = tf.sort(arry)
print("二维数组排序 升序:\n", arry_sort.numpy())
arry_sort_descending = tf.sort(arry, direction="DESCENDING")
print("二维数组排序 降序:\n", arry_sort_descending.numpy())
arry_argsort = tf.argsort(arry)
print("二维数组排序 升序索引:\n", arry_argsort)
2.正确率计算(top_k)
tf.math.top_k
arry = tf.random.uniform((3, 3), maxval= 10, dtype=tf.int32)
print(arry)
arry_topk = tf.math.top_k(arry, 2)
print(arry_topk.indices)
print(arry_topk.values)
3.计算Top5的正确率
def accuracy(y_pred, y_ture, k=(1,)):
max_k = max(k)
data_len = y_ture.shape[0]
y_pred = tf.math.top_k(y_pred, max_k).indices
y_pred = tf.transpose(y_pred, perm=[1, 0])
y_ture_b = tf.broadcast_to(y_ture, y_pred.shape)
correct = tf.equal(y_pred, y_ture_b)
res = []
for i in k:
correct_k = tf.cast(tf.reshape(correct[:i], [-1]), dtype=tf.float32)
correct_k = tf.reduce_sum(correct_k)
accy = correct_k * (100 / data_len)
res.append(accy.numpy())
return res
y_pred = tf.random.normal((10, 6))
y_pred = tf.math.softmax(y_pred, axis=-1)
print(y_pred)
y_true = tf.random.uniform((10,), maxval=6, dtype=tf.int32)
print(y_true)
y_pred_max = tf.argmax(y_pred, axis=1)
print(y_pred_max)
acc = accuracy(y_pred, y_true, (1, 2, 3, 4, 5))
print(acc)