【问题标题】:tensorflow v2 gradients not shown on tensorboard histograms张量板直方图上未显示张量流 v2 梯度
【发布时间】:2020-12-10 07:42:04
【问题描述】:

我有一个简单的神经网络,我正在尝试使用 tensorboard 通过使用如下回调来绘制梯度:

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()
]

然后,我在 fit 期间使用回调:

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

现在,当我检查张量板时,我可以在左侧过滤器上看到渐变,但直方图选项卡中没有显示任何内容:

我在这里缺少什么?我是否正确记录了梯度?

【问题讨论】:

  • 您的问题现在解决了吗?否则,请查看this,可能对您有所帮助。
  • 该链接使用 Tensorflow 1.x
  • 您好,我正在尝试做同样的事情:您是否掌握了这个?有什么解决办法吗?我正在尝试做同样的事情,但没有太多关于它的内容。
  • 嘿抱歉,还没有找到任何解决方案。希望有更好的文档。

标签: tensorflow2.0 tensorboard gradienttape


【解决方案1】:

看起来问题在于您在 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])) 

【讨论】:

  • 获取ValueError: Passed in object of type <class 'numpy.ndarray'>, not tf.Tensor 错误
  • @shaikmoeed 您的数据(_x_batch,_y_batch)很可能是一个 numpy 数组,而不是 tf.Tensor。您需要先转换它,然后才能在此上下文中使用它。我提出的解决方案只解决了梯度未发送到 tensorboard 的问题。代码的任何其他问题都超出了答案的范围。
  • 我想要类似的行为并尝试使用您的代码,但不明白 test_images_scaled_reshape[:100] 来自哪里?由于该函数是在 epoch 结束时应用的,您是否不想获取与该 epoch 对应的训练数据?
猜你喜欢
  • 2016-08-20
  • 2016-07-25
  • 1970-01-01
  • 1970-01-01
  • 2023-03-27
  • 2016-09-12
  • 2018-07-10
  • 1970-01-01
相关资源
最近更新 更多