2017-05-30 42 views
1

,一個variable_scope內的所有繼承reuse選項是這樣的:當我必須在它說的Tensorflow文件明確使用重用選項tensorflow

with tf.variable_scope("name", reuse=True): 
    # inherits reuse=True 

但我的問題是,當我例如使用這些輔助方法之一:

fc = tf.contrib.layers.fully_connected(input, 512, activation_fn=tf.nn.relu, weights_initializer=tf.contrib.layers.xavier_initializer(uniform=False)) 

norm = tf.contrib.layers.batch_norm(conv, 0.9, epsilon=1e-5, activation_fn=tf.nn.relu, scope=scope, fused=True) 

我必須設置的選項:reusescope明確如下:

fc = tf.contrib.layers.fully_connected(input, 512, activation_fn=tf.nn.relu, weights_initializer=tf.contrib.layers.xavier_initializer(uniform=False), scope=scope, reuse=True) 

norm = tf.contrib.layers.batch_norm(conv, 0.9, epsilon=1e-5, activation_fn=tf.nn.relu, scope=scope, reuse=True, is_training=self.is_training, fused=True) 

或這是如何工作的?

回答

1

我必須設置的選項:重用和範圍明確如下:

reuse參數設計重用現有的變量Sharing Variables在圖形不同OPS之間。在神經網絡訓練步驟中學習參數;因此要在驗證過程中使用這些學習過的參數,您可以使用reuse參數檢索變量,而無需重置值或不重新創建這些變量。

這是很好的做法,以保持reuse參數

# a usual CNN model definition with reuse parameter 
def model(input, reuse=None): 
    fc = tf.contrib.layers.fully_connected(input, 512,activation_fn=tf.nn.relu, 
     weights_initializer=tf.contrib.layers.xavier_initializer(uniform=False), 
     scope=scope, reuse=reuse) 

    norm = tf.contrib.layers.batch_norm(conv, 0.9, epsilon=1e-5, 
     activation_fn=tf.nn.relu, scope=scope, reuse=reuse, 
     is_training=self.is_training, fused=True) 
    ... 


# Now for training; setting reuse=None creates the graph variables 
some_ouput = model(input, reuse=None) 

# Now for validation; setting reuse=True; retrieve the learned variables for validation without creating new one. 
some_output = model(input, reuse=True) 
-2

首先,谷歌!這應該回答你的問題:Tensorflow variable scope: reuse if variable exists

但是,如果不是...... 如果實際重新使用模型的一部分,而不是如果使用圖層,則需要調用重用。比方說,你有一個函數定義爲:

def func(input,scope=scope, reuse=reuse): 
    fc = tf.contrib.layers.fully_connected(input, ..., scope=scope, reuse=reuse) 
    norm = tf.contrib.layers.batch_norm(fc, ..., scope=scope, reuse=reuse) 
    return norm 

範圍將定義的變量(閱讀更多有關範圍What's the difference of name scope and a variable scope in tensorflow?https://jasdeep06.github.io/posts/variable-sharing-in-tensorflow/Understanding Variable scope example in Tensorflow)命名空間,所以一旦您運行範圍的功能=「SCP」和input.shape =(1,2,3),你將無法使用相同的範圍和input.shape =(3,4,5)運行相同的函數,因爲具有給定範圍和不同形狀的變量已經存在。 因此,您應該在第二次調用函數時使用reuse = True。

+0

這不回答我的問題在所有的賽道!我在問,是否必須明確地設置範圍=範圍,重用=重用或者當我使用tf.variable_scope(name,reuse = True)作爲範圍時,可以保留它:.. – thigi

+0

也許我誤解了你,對不起。然而,你的問題可以通過閱讀範圍來解答。 https://www.tensorflow.org/programmers_guide/variable_scope 通常 - 不,您不需要再次將重用作爲參數。儘管如此,範圍並沒有太大的意義,因爲您編寫的代碼將始終與新的輸入一起工作。正如我所提到的,一旦你真正定義了你想要重用的模型,範圍就很有用。我希望這可以幫助你更多。 – Karaszka

相關問題