【问题标题】:Print all terms of loss function tensorflow 2.0打印损失函数 tensorflow 2.0 的所有项
【发布时间】:2020-04-04 13:45:58
【问题描述】:

我正在定义一个自定义损失函数。例如,让我们以loss function = L1 loss + L2 loss. 当我做model.fit_generator() 时,每批之后都会打印整体损失函数。但我想查看L1 lossL2 loss 的各个值。我怎样才能做到这一点? 我想知道各个术语的值以了解它们的相对比例。

  1. tf.print(l1_loss, output_stream=sys.stdout) 正在抛出异常,说 tensorflow.python.eager.core._FallbackException: This function does not handle the case of the path where all inputs are not already EagerTensors.

  2. 即使tf.print('---') 也只是在开头打印---,而不是每批都打印。

  3. tf.keras.backend.print_tensor(l1_loss) 没有打印任何内容

【问题讨论】:

  • 您尝试过sess.run(l1_loss)sess.run(l2_loss),以及必要的feed_dicts?
  • 我使用的是 tensorflow 2.0。我正在使用model.fit_generator() 训练模型。 sess.run()这里无处可做。

标签: python tensorflow logging tensorflow2.0 tf.keras


【解决方案1】:

没有看到您的代码,我只能猜测您没有使用 @tf.function 装饰器装饰您的自定义损失函数。

import numpy as np
import tensorflow as tf

@tf.function  # <-- Be sure to use this decorator.
def custom_loss(y_true, y_pred):
  loss = tf.reduce_mean(tf.math.abs(y_pred - y_true))
  tf.print(loss)  # <-- Use tf.print(), instead of print(). You can print not just 'loss', but any TF tensor in this function using this approach.
  return loss

model = tf.keras.Sequential()
model.add(tf.keras.layers.Dense(1, input_shape=[8]))
model.compile(loss=custom_loss, optimizer="sgd")

x_data = tf.data.Dataset.from_tensor_slices([np.ones(8)] * 100)
y_data = tf.data.Dataset.from_tensor_slices([np.ones(1)] * 100)
data = tf.data.Dataset.zip((x_data, y_data)).batch(2)

model.fit_generator(data, steps_per_epoch=10, epochs=2)

输出如下所示,它告诉您逐批的损失值。

Epoch 1/2
0.415590227  1/10 [==>...........................] - ETA: 0s - loss: 0.41560.325590253
0.235590339
0.145590425
0.0555904508
0.034409523
0.0555904508
0.034409523
0.0555904508
0.034409523 10/10 [==============================] - 0s 11ms/step - loss: 0.1392 Epoch 2/2
0.0555904508  1/10 [==>...........................] - ETA: 0s - loss: 0.05560.034409523
0.0555904508
0.034409523
0.0555904508
0.034409523
0.0555904508
0.034409523
0.0555904508
0.034409523 10/10 [==============================] - 0s 498us/step - loss: 0.0450

【讨论】:

  • 完美!我不知道tf.function 装饰器。这就是我所缺少的。使用该装饰器有什么注意事项,在使用之前我应该​​注意吗?在文档中,我用这个装饰器读到了类似eager execution 的内容。
  • 是否可以将回调方法写成tf.function。我正在寻找打印损失函数on_epoch_end 的每个损失项的方法。任何帮助表示赞赏!
  • @satyanarayanrao,虽然我不知道怎么做,但我确信它很容易实现。我建议您打开自己的新问题,因为您要问的内容与 OP 完全不同,您可能会得到更多回复。
猜你喜欢
  • 2020-11-05
  • 2020-07-28
  • 2020-01-21
  • 2016-02-23
  • 2019-12-16
  • 2018-03-25
  • 2020-03-16
  • 1970-01-01
  • 2021-10-24
相关资源
最近更新 更多