tensorflow - TensorFlow 2 和 Keras 中不同的正向和反向传播

标签 tensorflow keras tensorflow2.0

我在前向传递中训练神经网络,随机一半时间使用不可微分激活,将激活四舍五入为 0 或 1(二进制),另一半使用类似于Sigmoid(确切地说是饱和 Sigmoid)然而,在向后传递中,我们使用关于可微分函数的梯度,即使我们在前向传递中使用了不可微分的离散函数。到目前为止我的代码是:

diff_active = tf.math.maximum(sat_sigmoid_term1(feature), sat_sigmoid_term2(feature))
binary_masks = diff_active 
rand_cond = tf.random.uniform([1,])
cond = tf.constant(rand_cond, shape=[1,])
if cond <0.5:
        with tf.GradientTape() as tape:
            non_diff_active = tf.grad_pass_through(tf.keras.layers.Lambda(lambda x: tf.where(tf.math.greater(x,0), x, tf.zeros_like(x))))(feature)
            grads = tape.gradient(non_diff_active , feature)
            binary_masks = non_diff_active  
tf.math.multiply(binary_masks, feature)  

我的直觉是,通过这种方式,始终应用可微分激活(希望它的梯度始终包含在 bacl-prop 中)并且使用 tf.grad_pass_through() 我可以应用非可区分激活,同时用单位矩阵替换它的反向传播。但是,我不确定我对 tf.grad_pass_through() 的使用或我设置随机变量的方式是否正确以及行为是否符合预期?

最佳答案

您可以使用 tf.custom_gradient为此:

import tensorflow as tf

@tf.function
def sigmoid_grad(x):
    return tf.gradients(tf.math.sigmoid(x), x)[0]

@tf.custom_gradient
def sigmoid_or_bin(x, rand):
    rand = tf.convert_to_tensor(rand)
    out = tf.cond(rand > 0.5,
                  lambda: tf.math.sigmoid(x),
                  lambda: tf.dtypes.cast(x > 0, x.dtype))
    return out, lambda y: (y * sigmoid_grad(x), None)

# Test
tf.random.set_seed(0)
x = tf.random.uniform([4], -1, 1)
tf.print(x)
# [-0.416049719 -0.586867094 0.0707814693 0.122514963]
with tf.GradientTape() as t:
    t.watch(x)
    y = tf.math.sigmoid(x)
tf.print(y)
# [0.397462428 0.357354015 0.517688 0.530590475]
tf.print(t.gradient(y, x))
# [0.239486054 0.229652107 0.249687135 0.249064222]
with tf.GradientTape() as t:
    t.watch(x)
    y = sigmoid_or_bin(x, 0.2)
tf.print(y)
# [0 0 1 1]
tf.print(t.gradient(y, x))
# [0.239486054 0.229652107 0.249687135 0.249064222]
with tf.GradientTape() as t:
    t.watch(x)
    y = sigmoid_or_bin(x, 0.8)
tf.print(y)
# [0.397462428 0.357354015 0.517688 0.530590475]
tf.print(t.gradient(y, x))
# [0.239486054 0.229652107 0.249687135 0.249064222]

关于tensorflow - TensorFlow 2 和 Keras 中不同的正向和反向传播,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/62379895/

相关文章:

python - Tensorflow:修改隐藏状态的计算

tensorflow - Tensorflow 和 Theano 中图像数据集表示之间的差异

python - 如何将训练数据分成更小的批处理来解决内存错误

python - 如何恢复tensorflow2中的特定检查点(以实现提前停止)?

tensorflow - 如何随机旋转张量图像

python - 重命名失败;访问被拒绝的 Tensorflow

python - MNIST手写数字分类器的预测

tensorflow - 如何通过 conda 安装 tensorflow 插件

tensorflow - 使用 keras 和 tensorflow 作为后端在 aws sagemaker 中配置 GPU

keras:在模型中加载保存的模型权重以进行评估