gpt4 book ai didi

python - 使用优化器时,variable_scope 会导致 'variable does not exist'

转载 作者:行者123 更新时间:2023-11-30 08:49:32 29 4
gpt4 key购买 nike

Supoose 我有两个模型 foobar。假设 bar 已预训练并加载。我想定义 foo 的成本函数,如以下代码中粗略地描绘的那样(它实际上是一个自动编码器)。请注意,这是重现我的问题的最小示例,因此它们在数学上没有意义。

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 不会发生这种情况。任何解释和指示将不胜感激。

最佳答案

您的ValueError是由于在variable_scope.reuse==True中创建新变量引起的。

当您调用 Adam 的最小化函数时,变量是由 Adam 创建的,用于保存图中每个可训练变量的动量。

您已将reuse设置为True,因此默认的variable_scope.reuse==True。一旦将其设置为 True,重用状态就无法永远变回 False。然后,Adam 在状态reuse==True 下创建变量,这会引发错误。

解决方案是当设置variable_scope.reuse=True时,在图的默认作用域下添加一个子作用域,那么默认的scope.reuse仍然是False,而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)

关于python - 使用优化器时,variable_scope 会导致 'variable does not exist',我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42603702/

29 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com