我有两个模型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