python - 我应该如何实现计算整个预测的 tf.keras.Metric?
问题描述
该tf.keras.Metric
接口提供了一个有用的工具来实现附加指标,例如损失/准确性。该接口旨在在update_state(self, y_pred, y_true)
调用时更新批次,结果应在result(self)
. 然而,在实施 FID、Inception Score、Expected Calibration Error 等指标时,我们必须查看整个预测集,而不是单个样本的迭代视图。我应该如何在 Tensorflow 中实现这样的自定义指标?我应该使用其他 API 吗?
解决方案
据我了解你的问题;
class BinaryTruePositives(tf.keras.metrics.Metric):
def __init__(self, name='binary_true_positives', **kwargs):
super(BinaryTruePositives, self).__init__(name=name, **kwargs)
self.true_positives = self.add_weight(name='tp', initializer='zeros')
def update_state(self, y_true, y_pred, sample_weight=None):
y_true = tf.cast(y_true, tf.bool)
y_pred = tf.cast(y_pred, tf.bool)
values = tf.logical_and(tf.equal(y_true, True), tf.equal(y_pred, True))
values = tf.cast(values, self.dtype)
if sample_weight is not None:
sample_weight = tf.cast(sample_weight, self.dtype)
sample_weight = tf.broadcast_to(sample_weight, values.shape)
values = tf.multiply(values, sample_weight)
self.true_positives.assign_add(tf.reduce_sum(values))
def result(self):
return self.true_positives
[来自tf2 docs的示例]
在update_state()
我们实现度量计算功能的方法中。本质上,update_state()
为整个小批量返回一个。因此,在 tf2 中可以进行小批量评估。但是,为了支持批量评估指标,您还必须更新整个输入管道。
推荐阅读
- java - 如何获取合并报表的总页数
- vba - 如何使用查询结果填充 ComboBox
- android - 任务':app:processDebugManifest'的执行失败 - React Native
- vb.net - 可以获得文件夹的最后修改日期吗?
- sql - 如何判断 SQL Server 的情况?
- python - 函数未在 spyder 中列出
- vb.net - 防止 Rest API 中的重复
- extjs6.2 - actioncolumn:如何避免动作被多次触发
- postgresql - 如何根据外键作为另一个表上的主键自动填充行上的列
- node.js - 部署到 GCP App Engine,但不提供服务器端渲染页面