2017-10-09 38 views
0

他那裏,Tensorfow初始化一定範圍僅

我有一個關於在該變量的作用域被初始化,或至少控制,該變量的作用域是在運行期間使用的問題。

採取例如這個簡單的一段代碼

import numpy as np 
import tensorflow as tf 

with tf.variable_scope('0') as scope: 
    place_holder_batch_x = tf.Variable(np.random.rand(11,6), dtype=tf.float64) 
    place_holder_batch_y = tf.Variable(np.random.rand(8,5), dtype=tf.float64) 
    rnn_cell = tf.nn.rnn_cell.BasicRNNCell(3) 
    z = place_holder_batch_x*2 

with tf.variable_scope('1') as scope: 
    place_holder_batch_x = tf.Variable(np.random.rand(10,5), dtype=tf.float64) 
    place_holder_batch_y = tf.Variable(np.random.rand(9,6), dtype=tf.float64) 
    rnn_cell = tf.nn.rnn_cell.BasicRNNCell(4) 
    z = place_holder_batch_x*2 

init = tf.global_variables_initializer() 

sess = tf.Session() 
sess.run(init) 
print(sess.run(z).shape) 

如果我會運行此按原樣我會得到如在可變範圍定義的變量z的形狀「1」。 但是如何指定在會話期間使用哪個變量範圍?我找不到在stackoverflow或在文檔中的任何答案...

當然,我可以只重命名z的z1和z2 ...但我想繼續留在這兩個範圍看起來很像對方並使用相同的名稱...

回答

0

試試這個:

import numpy as np 
import tensorflow as tf 


g1 = tf.Graph() 
with g1.as_default() as g: 
    with tf.variable_scope('0') as scope: 
     place_holder_batch_x = tf.Variable(np.random.rand(11,6), dtype=tf.float64) 
     place_holder_batch_y = tf.Variable(np.random.rand(8,5), dtype=tf.float64) 
     rnn_cell = tf.nn.rnn_cell.BasicRNNCell(3) 
     z = place_holder_batch_x*2 
g2 = tf.Graph() 
with g2.as_default() as g: 
    with tf.variable_scope('1') as scope: 
     place_holder_batch_x = tf.Variable(np.random.rand(10,5), dtype=tf.float64) 
     place_holder_batch_y = tf.Variable(np.random.rand(9,6), dtype=tf.float64) 
     rnn_cell = tf.nn.rnn_cell.BasicRNNCell(4) 
     z = place_holder_batch_x*2 

tf.reset_graph_default() 

graph_to_be_used = g1 

with tf.session(graph = graph_to_be_used) as sess: 
    init = tf.global_variables_initializer() 

    sess.run(init) 
    print(sess.run(z).shape) 
+0

酷!謝謝你的回答,明天會試用。 但是,你能解釋一下這個背後的想法嗎?因爲本質上我們定義了兩次對變量集合的唯一ID ......爲什麼我們不能用一組範圍變量開始一個會話......或者換句話說,現在定義變量範圍的用法是什麼?因爲我們已經有了獨特的圖形標識符... – zwep

+0

等等..再想一想..我想我理解它。因爲一個Graph可以被構造成包含多個變量作用域(例如它可以共享變量)。 然後又出現了另一個問題......那就是爲什麼我沒有看到通常在代碼示例中定義這樣一個圖的用法?我認爲這是一種偏見嗎?或者使用它不太常見? (對不起,文字btw的數量...) – zwep