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