【问题标题】:Tensorflow cond doesn't stop gradient on the false branchTensorflow cond 不会在错误分支上停止梯度
【发布时间】:2017-07-29 15:35:48
【问题描述】:

我正在构建一个 RNN 模型,其中 init_state 可能来自两种情况之一。 1) 通过 feed_dict 从前一个时间步输出状态输入的静态 init_state。 2) 变量的一些函数,我称之为分数。

init_state = cell.zero_state(batch,tf.float32)
with tf.name_scope('hidden1'):
     weights_h1 = tf.Variable(
                        tf.truncated_normal([T, cells_dim],
                        stddev=1.0 / np.sqrt(T)),
                        name='weights')
     biases_h1 = tf.Variable(tf.zeros([cells_dim]),
                        name='biases')
     hidden1 = tf.nn.relu(tf.matmul(score, weights_h1) + biases_h1)

init_state2 = tf.cond(is_start, lambda: hidden1, lambda: init_state)

init_state2 然后用作 static_rnn 的输入,最终用于计算 loss 和 train_op。当 is_start 为 False 时,我希望 train_op 对 weights_h1 没有影响。但是,每次更新后权重都会发生变化。非常感谢任何帮助。

【问题讨论】:

  • 惰性求值仅适用于在 tf.cond 调用期间构造的张量。您构建图表的方式意味着无论is_start的值如何,都会评估所有张量@
  • 我尝试将 tf.name_scope('hidden1') 中的所有内容放在 python 函数 MLP() 中,并将中间 lambda 更改为 MLP。它会引发错误“无法将 feed_dict 键解释为张量:张量张量(“X:0”,shape=(20, 100),dtype=float32)不是此图的元素。”但是,这种变化根本不会影响 X。我在这里错过了什么?

标签: tensorflow


【解决方案1】:

这应该可行:

def return_init_state():
    init_state = cell.zero_state(batch,tf.float32)
    return init_state

def return_hidden_1():
    with tf.name_scope('hidden1'):
        weights_h1 = tf.Variable(
                            tf.truncated_normal([T, cells_dim],
                            stddev=1.0 / np.sqrt(T)),
                            name='weights')
        biases_h1 = tf.Variable(tf.zeros([cells_dim]),
                            name='biases')
        hidden1 = tf.nn.relu(tf.matmul(score, weights_h1) + biases_h1)

        return hidden1

init_state2 = tf.cond(is_start, lambda: return_hidden_1, lambda: return_init_state)

注意这些方法是如何在tf.cond 的上下文中调用的。因此,无论创建什么操作,都将在tf.cond 的上下文中。否则,在您的情况下,操作将以任何一种方式运行。

【讨论】:

  • 我也很困惑。我知道在前向分支中,如果两个分支不是在 tf.cond 的上下文中构造的,而是在之前构造的,它们都会被评估。我不明白的是,在反向传播期间,假分支上的梯度不是 0。梯度应该只传播到真正的分支(就像在 tf.max 函数中一样,不是吗?)
猜你喜欢
  • 1970-01-01
  • 2018-02-06
  • 1970-01-01
  • 2020-02-19
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2019-11-16
相关资源
最近更新 更多