【问题标题】:TensorFlow pass gradient unchanedTensorFlow pass 梯度不变
【发布时间】:2016-10-28 12:49:55
【问题描述】:

假设我在神经网络中使用了一些自定义操作binarizer。该操作采用Tensor 并构造一个新的Tensor。我想修改该操作,使其仅用于前向传递。在反向传播中,当计算梯度时,它应该只是通过到达它的梯度。

更具体的说,binarizer 是:

def binarizer(input):
    prob = tf.truediv(tf.add(1.0, input), 2.0)
    bernoulli = tf.contrib.distributions.Bernoulli(p=prob, dtype=tf.float32)
    return 2 * bernoulli.sample() - 1

然后我设置了我的网络:

# ...

h1_before_my_op = tf.nn.tanh(tf.matmul(x, W) + bias_h1)
h1 = binarizer(h1_before_b)

# ...

loss = tf.reduce_mean(tf.square(y - y_true))
train_step = tf.train.GradientDescentOptimizer(0.5).minimize(loss)

如何告诉 TensorFlow 在反向传递中跳过梯度计算?


我尝试按照this answer 中的描述定义自定义操作,但是:py_func 不能返回 Tensors,这不是它的用途——我明白了:

UnimplementedError(回溯见上文):不支持的对象类型张量

【问题讨论】:

  • 您希望您的子图在向后传递时表现得像 tf.identity,所以您可以在这里使用技巧 -- stackoverflow.com/questions/36456436/…
  • @YaroslavBulatov 不错!我今天终于有时间实现它,它似乎有效!

标签: python numpy tensorflow


【解决方案1】:

你正在寻找tf.stop_gradient(input, name=None):

停止梯度计算。

当在图中执行时,此操作按原样输出其输入张量。

h1 = binarizer(h1_before_b)
h1 = tf.stop_gradient(h1)

【讨论】:

  • 谢谢。但似乎这会停止渐变而不是传递渐变? IE。 h1 左侧的所有内容在我的测试中都没有收到梯度:与 h1 左侧的阶段相关的所有权重不会通过训练步骤更新,右侧的权重会...跨度>
猜你喜欢
  • 1970-01-01
  • 2019-11-16
  • 1970-01-01
  • 1970-01-01
  • 2017-04-30
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多