2017-08-21 17 views
0

TensorflowでseqGANを作成するだけです。TensorflowでRNNの変数を共有する方法

しかし変数を共有することはできません。

私はどのように再利用することを私に教えてください...以下のよう

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 

をコード目指し弁別を書きました。

答えて

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/は有用な例をたくさん持っています。

特定の例では、内部変数_スコープの名前をname+'RNN'と指定する必要はありません。 variable_scopeがネストされているので、RNNで十分です。 それ以外の場合は、再利用が正しく使用されているように見えますが、これは別のものであるname_scopeを比較しているだけです。 tf.global_variablesを見て、どのような変数が作成されたのか、そしてあなたが意図した通りに再利用しているのかを確認することで、二重にチェックすることができます。

私はそれが助けてくれることを願っています!

関連する問題