Supoose我有两个模型foo
和{bar
是预先训练并加载的。我想定义foo
的cost函数,大致如下面的代码所示(它实际上是一个自动编码器)。请注意,这是一个最小的例子来重现我的问题,所以它们在数学上没有意义。在
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 version 1.0),则会出现以下错误:
^{pr2}$但是,GradientDescentOptimizer
不会发生这种情况。如有任何解释和建议,我们将不胜感激。在
ValueError是由在变量中创建新变量引起的_scope.reuse==True. 在
当您调用Adam的minimize函数时,Adam创建了变量,用于保存图形中每个可训练变量的动量。在
您已经将reuse设置为True,因此是默认变量_scope.reuse==True. 一旦将重用状态设置为True,则不能永远将其更改回False。然后,Adam在state repuse==True下创建变量,这将引发一个错误。在
解决方案是在设置变量时在图的默认范围下添加一个子范围_scope.reuse=True,然后是默认值范围.再利用还是假的,而且亚当。最小化工作原理如下:
相关问题 更多 >
编程相关推荐