1

我有兩個模型foobar。假設bar被預訓練並加載。我想爲foo定義成本函數,大致在下面的代碼中描繪出來(它實際上是一個自動編碼器)。請注意,這是重現我的問題的一個最小示例,因此它們在數學上沒有意義。變量_scope導致'變量不存在'與優化器

import tensorflow as tf 

def foo(X): 
     with tf.variable_scope("foo"): 
       A = tf.get_variable("A",shape=[1]) 
     return tf.add(X,A) 

def bar(X): 
     with tf.variable_scope("bar"): 
       B = tf.get_variable("B",shape=[1]) 
     return tf.multiply(X,B) 

X = tf.placeholder("float") 

X_prime = foo(X) 

Y = bar(X) 
tf.get_variable_scope().reuse_variables() 
Y_prime = bar(X_prime) 


#foo(X) is manipulated with some other terms, but the point is foo is called again 
cost = foo(X) + tf.pow(Y-Y_prime,2) 

optimizer = tf.train.AdamOptimizer(learning_rate=0.01).minimize(cost) 

如果我運行該腳本(TF 1.0版),我收到以下錯誤:

ValueError: Variable foo/A/Adam/ does not exist, or was not created with tf.get_variable(). Did you mean to set reuse=None in VarScope? 

然而,這並不GradientDescentOptimizer發生。任何解釋和指針,將不勝感激。

+0

有人可以幫忙嗎? – user3813674

+0

你解決了你的問題嗎?在我看來,在設置全局''tf.get_variable_scope()。reuse_variables()''後,該行之後的所有變量都將查找現有變量。如果沒有這樣的變量,tensorflow會提示錯誤。像Momentum,Adam這樣的優化器,他們需要創建變量來存儲歷史漸變,以便「儘量減少」成本。解決這個問題的一個可能的方法是你可以在本地通過爲函數添加一個參數來設置''variable_scope(「foo」,reuse = reuse)'',而不是全局的。 – Seven

回答

0

您的ValueError是由在variable_scope.reuse == True中創建新變量引起的。

變量由Adam創建,當您調用Adam的最小化函數時,可以節省圖形中每個可訓練變量的動量。

您已將重用設置爲True,因此默認variable_scope.reuse == True。一旦將其設置爲True,重用狀態不能永久變回False。然後,Adam在狀態重用== True的情況下創建變量,這會引發錯誤。

的解決方案是增加一個子範圍下圖的默認範圍,當您設置variable_scope.reuse = True,則默認scope.reuse還是假,和Adam.minimize將工作,如下:

import tensorflow as tf 
def foo(X): 
     with tf.variable_scope("foo"): 
       A = tf.get_variable("A",shape=[1]) 
     return tf.add(X,A) 

def bar(X): 
     with tf.variable_scope("bar"): 
       B = tf.get_variable("B",shape=[1]) 
     return tf.multiply(X,B) 

X = tf.placeholder("float") 

with tf.variable_scope("for_reuse_scope"): 
    X_prime = foo(X) 
    Y = bar(X) 
    tf.get_variable_scope().reuse_variables() 
    Y_prime = bar(X_prime) 


#foo(X) is manipulated with some other terms, but the point is foo is called again 
cost = foo(X) + tf.pow(Y-Y_prime,2) 

optimizer = tf.train.AdamOptimizer(learning_rate=0.01).minimize(cost) 
+0

你需要把: 與tf.variable_scope(tf.get_variable_scope()) 其中運行在你的設備上環前... 如此,這樣做: 與tf.variable_scope(tf.get_variable_scope( )): for xrange(FLAGS.num_gpus): with tf.device('/ gpu:%d'%i): – BenJLI