Python 3.x 如何在Tensorflow上共享RNN的变量

Python 3.x 如何在Tensorflow上共享RNN的变量,python-3.x,tensorflow,Python 3.x,Tensorflow,我只是在Tensorflow上做seqGAN 但我不能共享变量 我写的代码目标鉴别器如下 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.variab

我只是在Tensorflow上做seqGAN

但我不能共享变量

我写的代码目标鉴别器如下

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

请教我如何重用。

variable\u scope
name\u scope
不直接交互<代码>变量\范围用于确定是创建新变量还是查找新变量。您应该使用
variable\u scope
get\u 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
有很多有用的例子

在您的特定示例中,不需要将内部变量的名称指定为
name+'RNN'
RNN
就足够了,因为
变量\u作用域
是嵌套的。 否则,在我看来,您正确地使用了重用,您只是比较了
name\u范围
,这是另一回事。您可以通过查看创建了哪些变量以及是否按预期方式重用这些变量来进行双重检查

我希望这有帮助