python - 在 TensorFlow 2.0 中实现引导式 BackProp?

标签 python tensorflow relu

我正在尝试使用 TensorFlow 2.0 应用引导式反向传播 ( https://arxiv.org/abs/1412.6806 )。要应用引导反向传播,我们需要修改 relu 梯度。 我读了How to apply Guided BackProp in Tensorflow 2.0?中的对话并尝试改编代码 https://gist.github.com/falcondai/561d5eec7fed9ebf48751d124a77b087 ,然而结果并不如我所料。我不确定我错过了什么。

这是我所拥有的(结合上面来源的代码):

import tensorflow as tf

@tf.RegisterGradient("GuidedRelu")
def _GuidedReluGrad(op, grad):
    dtype = op.inputs[0].dtype
    gate_f = tf.cast(op.outputs[0] > 0, dtype) #for f^l > 0
    gate_R = tf.cast(grad > 0, dtype) #for R^l+1 > 0
    return gate_f * gate_R * grad

with tf.compat.v1.get_default_graph().gradient_override_map({'Relu': 'GuidedRelu'}):
    with tf.GradientTape() as tape:
        x = tf.constant([10., 2.])
        tape.watch(x)
        y = tf.nn.relu(x)
        z = tf.reduce_sum(-y ** 2)
        print(x.numpy())
        print(y.numpy())
        print(z.numpy())
        print(tape.gradient(z, x).numpy())

输出为

[10.  2.]
[10.  2.]
-103.99999
[-20.  -4.]

而不是

[10.  2.]
[10.  2.]
-103.99999
[0.  0.]

最佳答案

在 tf2.0/2.1 中似乎没有一种干净的方法。我使用的解决方法是通过使用使用 @custom_gradient 的自定义 ReLU 更改 ReLU 来修改我的模型。我受到this thread的启发。虽然有点慢,但至少可以用。 TF 肯定会更新以再次支持渐变重新映射。希望同时对您有所帮助。

编辑:讨论该问题的问题 here .

关于python - 在 TensorFlow 2.0 中实现引导式 BackProp?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58593653/

相关文章:

tensorflow - tf.cond 和 if-else 有什么区别?

opencv - cv2.dnn.readNetFromDarknet 错误 : (-212:Parsing error) Unsupported activation: relu in function 'cv::dnn::darknet::ReadDarknetFromCfgStream'

带有字节序转换的 Python 文件 Slurp

python - 如何将 (x,y) 对列表映射到 Pool.map 中的函数 f(x,y)?

python - 如何使用 Haystack/Whoosh 和 Django 索引外键 CharField?

Python,使用difflib逐字比较两个句子

python - Keras:我到底需要改变哪些维度?

python - 如何解决操作系统错误 : [Errno 22] Invalid argument:

python - 当使用 .clamp 而不是 torch.relu 时,Pytorch Autograd 会给出不同的渐变