Tensorflow 2.0下,如何使用tf.summary?

Under Tensorflow 2.0, how to use tf.summary?

好像tf.summary在TF2.0下的用法和TF1.x不一样。如果我想在 TensorBoard 中可视化多个标量(例如 train_loss、val_loss 等),如何在代码中实现 tf.summary。我认为可能是:

writer = tf.summary.create_file_writer('summaries')
for epoch in range(epochs):
    ...
    train_loss = ...
    val_loss = ...
    tf.summary.scalar('train_loss', train_loss)
    tf.summary.scalar('val_loss', val_loss)
    writer.flush()

但是没用。我认为问题可能出在使用 write.flush().

在tensorflow 2.0中,您需要通过.as_default()设置默认编写器。此外,step 参数必须在摘要操作中传递。更多详情可见here

writer = tf.summary.create_file_writer("summaries")

for epoch in range(epochs):
    train_loss = ...
    val_loss = ...
    with writer.as_default():
      tf.summary.scalar('train_loss', train_loss, step=epoch)
      tf.summary.scalar('val_loss', val_loss, step=epoch)
    writer.flush()