如何在Keras上的Tensorboard中添加文本摘要?

时间:2018-09-22 03:44:12

标签: tensorflow keras tensorboard

使用Keras时如何向Tensorboard添加文本摘要?

我已经设置了一个Tensorboard回调,但是我对如何添加文本摘要一无所知。

例如,我想将运行中使用的不同参数的文本摘要添加到Tensorboard中,以便进行文档记录,并且在我重新访问运行日志时不会丢失。

一种选择似乎是将所有参数详细信息都包含到日志文件的目录名中,但这看起来很累人。

如何更好地解决这个问题?

3 个答案:

答案 0 :(得分:3)

对于其他需要此功能的人,我最终编写了一个扩展了Keras Tensorboard的自定义回调。稍后我可能会记录比摘要更多的内容,我们可以将其扩展为在不同事件上记录更多内容。我简化了another question - to add plot

from keras.callbacks import TensorBoard
import tensorflow as tf

class LoggingTensorBoard(TensorBoard):    

    def __init__(self, log_dir, settings_str_to_log, **kwargs):
        super(LoggingTensorBoard, self).__init__(log_dir, **kwargs)

        self.settings_str = settings_str_to_log

    def on_train_begin(self, logs=None):
        TensorBoard.on_train_begin(self, logs=logs)

        tensor =  tf.convert_to_tensor(self.settings_str)
        summary = tf.summary.text ("Run Settings", tensor)

        with  tf.Session() as sess:
            s = sess.run(summary)
            self.writer.add_summary(s)

创建此Tensorboard的实例并添加到model.fit回调中,您的settings_str_to_log将显示在Tensorboard的“文本”选项卡中。

答案 1 :(得分:1)

我没有看他们是否删除或移动了默认书写器。但是您可以创建自己的作家,它会在Tensorboard中显示为文本摘要。由于TF2.0默认为“急切”模式,因此无需会话。

dir_name = os.path.join("your_log_dir", "Text Summary")
writer = tf.summary.create_file_writer(logdir=dir_name)

with writer.as_default():
    tf.summary.text(name="Run_Settings", data= self.settings_str, step=0)

答案 2 :(得分:0)

这适用于tf 2.1 2.2和2.3

class TensorBoardExtended(TensorBoard):
    """
    Extended Tensorboard log that allows to add text

    By default logs:
    - host
    - gpus available

    Parameters
    -------------
    text_dict_to_log : dict
        Dictionary with key, value string that will be logged with Tensorboard
    kwargs : dict
        All the other parameters that are fed to Tensorboard
    """
    def __init__(self, text_dict_to_log=None, **kwargs):
        super().__init__(**kwargs)
        self.text_dict_to_log = text_dict_to_log

    def on_train_begin(self, logs=None):
        # pylint: disable= E1101
        super().on_train_begin(logs=logs)

        try:
            writer = self._get_writer('train')
        except AttributeError: # this is due to differences between tf21, 22 and 23
            writer = self._train_writer

        with writer.as_default():
            for key, value in self.text_dict_to_log.items():
                tf.summary.text(key, tf.convert_to_tensor(value), step=0)