Search code examples
pythontensorflowkerascallbacklstm

How do I plot data in a single figure instead of 2 in Tensorboard generated using tf.summary.scalar() on metrics procured from a custom callback?


I have used the following code to plot 2 scalar plots in Tensorboard on metrics procured from Custom ROC-AUC score callback.

for epoch in range(len(history.history['roc_train'])):
    with train_summary_writer.as_default():
        tf.summary.scalar('roc_auc_train', history.history['roc_train'][epoch], step=epoch)
        tf.summary.scalar('roc_auc_val', history.history['roc_val'][epoch], step=epoch)

plots in Tensorboard:

enter image description here

enter image description here

How do I get them both in the same figure? Please help.


Solution

  • Create two different file_writer instances, and using the same name (roc_auc in this example) call the with statement on the context of the desired plot.

    import tensorflow as tf
    import numpy as np
    import os
    import time
    
    now = time.localtime()
    subdir = time.strftime("%d-%b-%Y_%H.%M.%S", now)
    
    summary_train = os.path.join("stackoverflow", subdir, "train")
    summary_val = os.path.join("stackoverflow", subdir, "val")
    
    writer_train = tf.summary.create_file_writer(summary_train)
    writer_val = tf.summary.create_file_writer(summary_val)
    
    for epoch in range(200):
        with writer_train.as_default():
            tf.summary.scalar(name="roc_auc", data=-np.math.exp(-(epoch/30))+1, step=epoch)
        with writer_val.as_default():
            tf.summary.scalar(name="roc_auc", data=-np.math.exp(-(epoch/15))+1, step=epoch)
    

    enter image description here