如何在Tensorflow上共享RNN的变量

时间:2017-08-21 13:13:36

标签: python-3.x tensorflow

我只是在Tensorflow上制作seqGAN。

但我不能分享变数。

我编写了一个针对Discriminator的代码,如下所示......

import tensorflow as tf 
def discriminator(x, args, name, reuse=False): 
    with tf.variable_scope(name, reuse=reuse) as scope:
        print(tf.contrib.framework.get_name_scope())

        with tf.variable_scope(name+"RNN", reuse=reuse) as scope:
            cell_ = tf.contrib.rnn.GRUCell(args.dis_rnn_size, reuse=reuse)
            rnn_outputs, _= tf.nn.dynamic_rnn(cell_, x, initial_state=cell_.zero_state(batch_size=args.batch_size, dtype=tf.float32), dtype=tf.float32) 

        with tf.variable_scope(name+"Dense", reuse=reuse) as scope:
            logits = tf.layers.dense(rnn_outputs[:,-1,:], 1, activation=tf.nn.sigmoid, reuse=reuse)

    return logits

discriminator(fake, args, "D_", reuse=False) #printed D_
discriminator(real, args, "D_", reuse=True) #printed D_1

请教我如何重复使用。

1 个答案:

答案 0 :(得分:0)

variable_scope不会直接与name_scope互动。 variable_scope用于确定是创建新变量还是查找新变量。您应该variable_scopeget_variable一起使用来完成此操作。

以下是一些例子:

with tf.variable_scope("foo") as foo_scope:
    # A new variable will be created.
    v = tf.get_variable("v", [1])
with tf.variable_scope(foo_scope)
    # A new variable will be created.
    w = tf.get_variable("w", [1])
with tf.variable_scope(foo_scope, reuse=True)
    # Both variables will be reused.
    v1 = tf.get_variable("v", [1])
    w1 = tf.get_variable("w", [1])
with tf.variable_scope("foo", reuse=True)
    # Both variables will be reused.
    v2 = tf.get_variable("v", [1])
    w2 = tf.get_variable("w", [1])
with tf.variable_scope("foo", reuse=False)
    # New variables will be created.
    v3 = tf.get_variable("v", [1])
    w3 = tf.get_variable("w", [1])
assert v1 is v
assert w1 is w
assert v2 is v
assert w2 is w
assert v3 is not v
assert w3 is not w

https://www.tensorflow.org/versions/r0.12/how_tos/variable_scope/有很多有用的例子。

在您的特定示例中,您不需要将内部variable_scopes的名称指定为name+'RNN'。由于RNN是嵌套的,因此variable_scope就足够了。 否则,我认为您正在使用重用,您只是比较name_scope这是另一回事。您可以通过查看tf.global_variables进行仔细检查,看看创建了哪些变量以及您是否按照预期的方式重复使用。

我希望有所帮助!

相关问题