我有兩個模型foo
和bar
。假設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
發生。任何解釋和指針,將不勝感激。
有人可以幫忙嗎? – user3813674
你解決了你的問題嗎?在我看來,在設置全局''tf.get_variable_scope()。reuse_variables()''後,該行之後的所有變量都將查找現有變量。如果沒有這樣的變量,tensorflow會提示錯誤。像Momentum,Adam這樣的優化器,他們需要創建變量來存儲歷史漸變,以便「儘量減少」成本。解決這個問題的一個可能的方法是你可以在本地通過爲函數添加一個參數來設置''variable_scope(「foo」,reuse = reuse)'',而不是全局的。 – Seven