tensorflow v2 그라디언트가 텐서 보드 히스토그램에 표시되지 않음

Aug 21 2020

다음과 같이 콜백을 사용하여 텐서 보드를 사용하여 그라디언트를 플로팅하려는 간단한 신경망이 있습니다.

class GradientCallback(tf.keras.callbacks.Callback):
    console = False
    count = 0
    run_count = 0

    def on_epoch_end(self, epoch, logs=None):
        weights = [w for w in self.model.trainable_weights if 'dense' in w.name and 'bias' in w.name]
        self.run_count += 1
        run_dir = logdir+"/gradients/run-" + str(self.run_count)
        with tf.summary.create_file_writer(run_dir).as_default(),tf.GradientTape() as g:
          # use test data to calculate the gradients
          _x_batch = test_images_scaled_reshaped[:100]
          _y_batch = test_labels_enc[:100]
          g.watch(_x_batch)
          _y_pred = self.model(_x_batch)  # forward-propagation
          per_sample_losses = tf.keras.losses.categorical_crossentropy(_y_batch, _y_pred) 
          average_loss = tf.reduce_mean(per_sample_losses) # Compute the loss value
          gradients = g.gradient(average_loss, self.model.weights) # Compute the gradient

        for t in gradients:
          tf.summary.histogram(str(self.count), data=t)
          self.count+=1
          if self.console:
                print('Tensor: {}'.format(t.name))
                print('{}\n'.format(K.get_value(t)[:10]))

# Set up logging
!rm -rf ./logs/ # clear old logs
from datetime import datetime
import os
root_logdir = "logs"
run_id = datetime.now().strftime("%Y%m%d-%H%M%S")
logdir = os.path.join(root_logdir, run_id)


# register callbacks, this will be used for tensor board latter
callbacks = [
    tf.keras.callbacks.TensorBoard( log_dir=logdir, histogram_freq=1, 
                                   write_images=True, write_grads = True ),
    GradientCallback()
]

그런 다음 적합 중에 콜백을 다음과 같이 사용합니다.

network.fit(train_pipe, epochs = epochs,batch_size = batch_size, validation_data = val_pipe, callbacks=callbacks)

이제 텐서 보드를 확인하면 왼쪽 필터에 그라디언트가 표시되지만 히스토그램 탭에는 아무것도 표시되지 않습니다.

내가 여기서 무엇을 놓치고 있습니까? 그래디언트를 올바르게 기록하고 있습니까?

답변

J.G Feb 09 2021 at 18:16

문제는 tf 요약 작성자의 컨텍스트 외부에서 히스토그램을 작성한다는 것입니다. 그에 따라 코드를 변경했습니다. 그러나 나는 그것을 시도하지 않았습니다.

class GradientCallback(tf.keras.callbacks.Callback):
    console = False
    count = 0
    run_count = 0

    def on_epoch_end(self, epoch, logs=None):
        weights = [w for w in self.model.trainable_weights if 'dense' in w.name and 'bias' in w.name]
        self.run_count += 1
        run_dir = logdir+"/gradients/run-" + str(self.run_count)
        with tf.summary.create_file_writer(run_dir).as_default()
          with tf.GradientTape() as g:
            # use test data to calculate the gradients
            _x_batch = test_images_scaled_reshaped[:100]
            _y_batch = test_labels_enc[:100]
            g.watch(_x_batch)
            _y_pred = self.model(_x_batch)  # forward-propagation
            per_sample_losses = tf.keras.losses.categorical_crossentropy(_y_batch, _y_pred) 
            average_loss = tf.reduce_mean(per_sample_losses) # Compute the loss value
            gradients = g.gradient(average_loss, self.model.weights) # Compute the gradient

          for nr, grad in enumerate(gradients):
            tf.summary.histogram(str(nr), data=grad)
            if self.console:
                  print('Tensor: {}'.format(grad.name))
                  print('{}\n'.format(K.get_value(grad)[:10]))