python - TensorFlow 指标:top-N 准确率
问题描述
我正在使用add_metric尝试创建一个自定义指标来计算分类器的前 3 位准确度。据我所知,这是:
def custom_metrics(labels, predictions):
# labels => Tensor("fifo_queue_DequeueUpTo:422", shape=(?,), dtype=int64)
# predictions => {
# 'logits': <tf.Tensor 'dnn/logits/BiasAdd:0' shape=(?, 26) dtype=float32>,
# 'probabilities': <tf.Tensor 'dnn/head/predictions/probabilities:0' shape=(?, 26) dtype=float32>,
# 'class_ids': <tf.Tensor 'dnn/head/predictions/ExpandDims:0' shape=(?, 1) dtype=int64>,
# 'classes': <tf.Tensor 'dnn/head/predictions/str_classes:0' shape=(?, 1) dtype=string>
# }
查看现有的实现tf.metrics
,一切都是使用 tf ops 实现的。我怎样才能实现前 3 名的准确性?
解决方案
如果您想自己实现它tf.nn.in_top_k
非常有用 - 它返回一个布尔数组,指示目标是否在前 k 个预测中。你只需要取结果的平均值:
def custom_metrics(labels, predictions):
return tf.metrics.mean(tf.nn.in_top_k(predictions=predictions, targets=labels, k=3))
你也可以导入它:
from tf.keras.metrics import top_k_categorical_accuracy
推荐阅读
- maven - Maven:从 Nexus 快照存储库下载旧快照而不是最新快照
- node.js - 制作聊天应用程序
- python-3.x - 使用 python jupyter 从列中选择特定字段
- meshlab - 如何在 Chrome 操作系统上下载 SlicerMorph?
- javascript - 如何在javascript中合并两棵树?
- r - 在 R 中使用 dplyr 循环获取异常值数据
- reactjs - 如何更改 REACT JS 中的 react-mathjax-preview 字体大小和字体?
- mysql - Mac localhost 上的 mySQL 超时
- php - 在 REST API 前端的发布后面板中更改 wordpress 站点地址
- mysql - 同一列上的多个索引