首页 > 解决方案 > 每批更新损失值以获得平均历元损失

问题描述

我想创建一个类似于您可以使用 tf.metrics 及其 update_op 值获得的操作。当您在 tf 中执行此操作时:

acc, update_op = tf.metrics.accuracy(tf.argmax(probs, 1), labels, name="accuracy")

update_op值在每次调用中更新

所以我想对损失做同样的事情。我尝试了以下代码: update_loss = tf.Variable(0., name="loss")

loss = tf.reduce_mean(tf.nn.sparse_softmax_cross_entropy_with_logits(logits=model.logits, labels=labels))
update_loss.assign(update_loss + loss)

但我总是跑:

init_vars = [tf.local_variables_initializer(), 

tf.global_variables_initializer()]
with tf.Session() as sess:
    loss_val = sess.run(update_loss)

我得到的值为 0。知道吗?

编辑:

我必须指出执行过程中张量损失的值不为零

标签: pythontensorflow

解决方案


好的,我发现了一个可行的解决方案,但它并没有真正解决我的疑问......基于这篇文章(5.2 Tensorflow - Batch accuracy)

它包括创建一个函数,该函数使用最后获得的损失值,并通过 feed_dict 将其传递给一个函数,该函数使用累积值更新占位符:

session.run(tf_metric_update, feed_dict=feed_dict)

推荐阅读