Слияние 2 участков в TensorBoard 2 с TensorFlow 2 - PullRequest
0 голосов
/ 01 октября 2019

Я хотел бы объединить на одном графике и точность, и вспомнить, используя Tensorflow и Tensorboard V2. Я нашел много примеров для предыдущих версий, но ни один из них не работает в моем случае.

Я создал обратный вызов Keras, который вычисляет точность и отзыв, затем я вызываю сводку по тензорному потоку, чтобы записать их в один и тот же регистратор. Я могу визуализировать их в Tensorboard, но на 2 отдельных участках.

Class ClassificationReport(Callback):
    def __init__(self, data_generator, steps, label_names, log_directory):
        """
        Instantiator
        :param data_generator: the data generator that produces the input data
        :param steps: int, batch size
        :param data_type, string, 'training', 'validation' or 'test', used a prefix in the logs
        :param log_directory: pathlib2 path to the TensorBoard log directory

        """

        self.data_generator = data_generator
        self.steps = steps
        self.data_type = data_type
        self.logger = tensorflow.summary.create_file_writer(str(log_directory / self.data_type))

        # names of the scalar to consider in the sklearn classification report
        self._scalar_names = ['precision', 'recall']

    def on_epoch_end(self, epoch, logs={}):
        """
        log the precision and recall

        :param epoch: int, number of epochs
        :param logs: the Keras dictionary where the metrics are stored
        """

        y_true = numpy.zeros(self.steps)
        y_predicted = numpy.zeros(self.steps)

       ...Here I fetch y_true and y_predicted with the data_generator

        # The current report is calculated by SciKit-Learn
        current_report = classification_report(y_true, y_predicted, output_dict=True)

        with self.logger.as_default():
            for scalar_name in self._scalar_names:
                tensorflow.summary.scalar(
                    name="{} / macro average / {}".format(self.data_type, scalar_name),
                    data=current_report['macro avg'][scalar_name],
                    step=epoch)

        return super().on_epoch_end(epoch, logs)

Насколько я понимаю логику Tensorboard 2, кажется, что невозможно построить 2 скалярных резюме на одном графике ... На этом этапе приветствуются любые советы.

1 Ответ

0 голосов
/ 01 октября 2019

Используйте два разных модуля записи с одним и тем же скалярным сводным именем.

import numpy as np
import tensorflow as tf

logger1 = tf.summary.create_file_writer('logs/scalar/precision')
logger2 = tf.summary.create_file_writer('logs/scalar/recall')

precision = np.random.uniform(size=10)
recall = np.random.uniform(size=10)

for i in range(10):
    with logger1.as_default():
        tf.summary.scalar(name='precision-recall', data=precision[i], step=i)
    with logger2.as_default():
        tf.summary.scalar(name='precision-recall', data=recall[i], step=i)

тензорная доска --logdir logs / scalar

enter image description here

Из этого ответа, адаптированного для tf2: https://stackoverflow.com/a/38718948/5597718

...