variable_scope使用Optimiz导致“variable does not exist”(变量不存在)

2024-10-17 08:26:45 发布

您现在位置:Python中文网/ 问答频道 /正文

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不会发生这种情况。如有任何解释和建议,我们将不胜感激。在


Tags: 模型getreturnfooistfdefwith
1条回答
网友
1楼 · 发布于 2024-10-17 08:26:45

ValueError是由在变量中创建新变量引起的_scope.reuse==True. 在

当您调用Adam的minimize函数时,Adam创建了变量,用于保存图形中每个可训练变量的动量。在

您已经将reuse设置为True,因此是默认变量_scope.reuse==True. 一旦将重用状态设置为True,则不能永远将其更改回False。然后,Adam在state repuse==True下创建变量,这将引发一个错误。在

解决方案是在设置变量时在图的默认范围下添加一个子范围_scope.reuse=True,然后是默认值范围.再利用还是假的,而且亚当。最小化工作原理如下:

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)

相关问题 更多 >