【问题标题】:TensorFlow: How can I inspect gradients and weights in eager execution?TensorFlow:如何在 Eager Execution 中检查梯度和权重?
【发布时间】:2020-01-10 18:43:48
【问题描述】:

我在 Eager Execution 中使用 TensorFlow 1.12,并且我想在训练期间检查不同点的梯度值和权重以进行调试。 This answer 使用 TensorBoard 来获得漂亮的权重和梯度分布图,这正是我想要的。但是,当我使用Keras' TensorBoard callback 时,我得到了这个:

WARNING:tensorflow:Weight and gradient histograms not supported for eagerexecution, setting `histogram_freq` to `0`.

换句话说,这与急切执行不兼容。有没有其他方法可以打印梯度和/或权重?大多数非 TensorBoard 的答案似乎都依赖于基于图形的执行。

【问题讨论】:

    标签: tensorflow gradient-descent eager-execution


    【解决方案1】:

    在 Eager Execution 中,您可以直接打印权重。至于梯度,您可以使用tf.GradientTape 来获取损失函数相对于某些权重的梯度。这是一个显示如何打印渐变和权重的示例:

    import tensorflow as tf
    
    tf.enable_eager_execution()
    
    x = tf.ones(shape=(4, 3))
    y = tf.ones(shape=(4, 1))
    dense = tf.layers.Dense(1)
    
    # Print gradients
    with tf.GradientTape() as t:
        h = dense(x)
        loss = tf.losses.mean_squared_error(y, h)
    gradients = t.gradient(loss, dense.kernel)
    print('Gradients: ', gradients)
    
    # Print weights
    weights = dense.get_weights()
    print('Weights: ', weights)
    

    【讨论】:

    • 感谢您的帮助!此方法可以与tf.fit() 结合使用,以便在多个时期打印渐变吗?由于该函数抽象为损失获取和权重更新,我不知道如何获取(内核),例如,我的输入层和损失“在同一个地方”,并将它们提供给 t.gradient 函数.
    • @EmielBoss 你的意思是tf.keras.Model.fit?如果是这种情况,您可以 (1) 不使用 tf.keras.Model.fit 实现您的自定义训练算法或 (2) 实现 custom keras callback (其中打印权重/梯度,例如在方法 on_epoch_end 中)并将其传递给tf.keras.Model.fit 的参数 callbacks
    猜你喜欢
    • 2019-11-04
    • 2019-02-13
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-02-06
    • 1970-01-01
    • 1970-01-01
    • 2023-03-13
    相关资源
    最近更新 更多