在TensorFlow中,我想在函数内定义一个变量,进行一些处理并根据一些计算返回一个值。但是,我无法在函数内部初始化变量。这是代码的最小示例:
import tensorflow as tf
def foo():
x = tf.Variable(tf.ones([1]))
y = tf.ones([1])
return x+y
if __name__ == '__main__':
with tf.Session() as sess:
init = tf.global_variables_initializer()
sess.run(init)
print(sess.run(foo()))
Run Code Online (Sandbox Code Playgroud)
运行代码会产生以下错误:
tensorflow.python.framework.errors_impl.FailedPreconditionError: Attempting to use uninitialized value Variable
Run Code Online (Sandbox Code Playgroud)
小智 7
在初始化所有变量之前,根本没有调用函数foo()。因此它无法初始化foo()中的变量。我们需要在运行会话之前调用该函数。
import tensorflow as tf
def foo():
x=tf.Variable(tf.zeros([1]))
y=tf.ones([1])
return x+y
with tf.Session() as sess:
result=foo()
init=tf.global_variables_initializer()
sess.run(init)
print(sess.run(result))
Run Code Online (Sandbox Code Playgroud)