1 Star 0 Fork 0

nell332/i3d_machine_learning

加入 Gitee
与超过 1200万 开发者一起发现、参与优秀开源项目,私有仓库也完全免费 :)
免费加入
文件
克隆/下载
topk_accuracy.py 898 Bytes
一键复制 编辑 原始数据 按行查看 历史
nell332 提交于 2024-04-18 11:19 . 1
import tensorflow as tf
def accuracy(output, target, topk=(1,)):
max_k = max(topk)
batch_size = target.shape[0]
pred = tf.math.top_k(output, max_k).indices
pred = tf.transpose(pred, perm=[1, 0])
target_ = tf.broadcast_to(target, pred.shape)
correct = tf.equal(pred, target_) # [k, b]
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
output = tf.random.normal((10, 6))
output = tf.math.softmax(output, axis=1)
target = tf.random.uniform([10], maxval=6, dtype=tf.int32)
print('prob:', output.numpy())
pred = tf.argmax(output, axis=1)
print('pred:', pred.numpy())
print('target:', target.numpy())
acc = accuracy(output, target, topk=(1, 2, 3, 4, 5, 6))
print('top-1-6 acc:', acc)
Loading...
马建仓 AI 助手
尝试更多
代码解读
代码找茬
代码优化
Python
1
https://gitee.com/nell332/i3d_machine_learning.git
git@gitee.com:nell332/i3d_machine_learning.git
nell332
i3d_machine_learning
i3d_machine_learning
master

搜索帮助