【问题标题】:Manually set gradient values in TensorFlow and use them in backpropagation在 TensorFlow 中手动设置梯度值并在反向传播中使用它们
【发布时间】:2020-12-14 03:59:44
【问题描述】:

为了确保这不是 XY 问题,我将描述情况:

我正在使用 keras/TensorFlow 构建一个 NN,而我想使用的损失函数似乎对 TF 是不可微分的。用tf.py_function 包裹它不起作用,因为渐变都是None。这种损失不是微不足道的,它是用完全不同的框架编写的。我意识到最直接的方法是使用 tf 函数重写损失,但这不可行(至少现在是这样)。

网络的最后一层是具有softmax输出的全连接层tf.keras.layers.Dense(n_labels, activation='softmax')。通过其他方式(不是 tf),我可以获得损失 w.r.t 的(数字)梯度。该层的输出。所以这给了我一个想法:是否可以在训练阶段手动设置这个梯度,然后让 Tensorflow 将它们传播到网络的其余部分以更新权重?至少在我看来,这会规避不可微损失的问题,但我不清楚损失是否真的会被优化或如何编码。

非常感谢

【问题讨论】:

  • 我还不清楚你的损失函数的性质是什么,但如果你愿意,你可以在 tf 中定义一个自定义的损失函数并可以用来训练模型
  • So this gave me an idea: would it be possible to manually set this gradients in the training phase and then let Tensorflow propagate them to the rest of the net to update the weights? 这个问题是tf.keras 默认在图形模式下训练,所以当你在 Keras 放置的保险杠之外太远时很容易遇到OperatorNotAllowedInGraph 错误。我认为正确的问题是如何表达你在张量流中的损失
  • 你想手动计算最后一层的梯度,让tf计算剩下的梯度?
  • 您应该可以使用tf.custom_gradient 做到这一点,即使您需要将部分或全部包裹在tf.py_function 或tf.numpy_function 中。
  • @bernie 创建一个layer with a custom gradient,您可以在其中手动设置渐变值。然后 tf 会将该值反向传播到之前的层。

标签: python tensorflow keras backpropagation loss-function


【解决方案1】:

您并没有真正提供太多细节,但作为一个总体思路,您可以使用 tf.custom_gradient 和 tf.numpy_function 或 tf.py_function 从 TensorFlow 中计算您的操作的值和梯度(以牺牲一些开销,加上这些函数的文档中所述的限制)。例如,像这样:

import tensorflow as tf
import numpy as np

# Some operation that you can only compute with NumPy
def my_operation_np(x):
    return np.square(x)

# The gradient of the operation computed with NumPy too
def my_operation_grad_np(x, y, dy):
    # In this example you could also pass only `x` here and
    # do the `* dy` bit in the TensorFlow gradient function.
    # That might reduce the amount of memory transfer between
    # TensorFlow and NumPy.
    return np.multiply(2, x) * dy

# TensorFlow wrapper for the operation
@tf.custom_gradient
def my_operation(x):
    y = tf.numpy_function(my_operation_np, [x], x.dtype)
    def grad(dy):
        return tf.numpy_function(my_operation_grad_np, [x, y, dy], x.dtype)
    return y, grad

# Test
with tf.GradientTape() as tape:
    x = tf.constant([1., 2., 3.])
    tape.watch(x)
    y = my_operation(x)
g = tape.gradient(y, x)
tf.print(g)
# [2 4 6]

【讨论】:

    猜你喜欢
    • 2017-10-25
    • 2020-01-07
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-05-08
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多