【问题标题】:Running the same RNN over two tensors in tensorflow在 tensorflow 中的两个张量上运行相同的 RNN
【发布时间】:2017-03-19 17:41:06
【问题描述】:

我想在 tensorflow 中的两个张量上运行相同的 RNN。我当前的解决方案如下所示:

cell = tf.nn.rnn_cell.GRUCell(cell_size)

with tf.variable_scope("encoder", reuse=None):
    out1 = tf.nn.dynamic_rnn(cell, tensor1, dtype=tf.float32)

with tf.variable_scope("encoder", reuse=True):
    out2 = tf.nn.dynamic_rnn(cell, tensor2, dtype=tf.float32)

这是确保两个 RNN 操作之间权重共享的最佳方式吗?

【问题讨论】:

    标签: tensorflow


    【解决方案1】:

    是的,我基本上就是这样做的。对于像这样一个非常简单的模型,这并不重要,但对于更复杂的模型,我会定义一个函数来构建图形。

    def makeEncoder(input_tensor):
        cell = tf.nn.rnn_cell.GRUCell(cell_size)
        return tf.nn.dynamic_rnn(cell, tensor1, dtype=tf.float32)
    
    with tf.variable_scope('encoder') as scope:
        out1 = makeEncoder(tensor1)
        scope.reuse_variables()
        out2 = makeEncoder(tensor2)
    

    另一种方法是使用tf.cond(...) 作为开关,根据布尔占位符在输入之间进行切换。然后他们将只去一个输出。我发现这可能会有点混乱。即使你真的只需要一个,你也需要提供两个输入。我认为我的第一个解决方案是最好的。

    【讨论】:

    • 感谢您的建议!
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-12-05
    • 1970-01-01
    • 1970-01-01
    • 2022-12-11
    相关资源
    最近更新 更多