&引用;“未初始化值”;将tensorflow代码包装到python函数时出错
错误是“试图使用未初始化的值状态变量”。但是我认为这段代码应该初始化这个值 这是我的代码,谢谢你:&引用;“未初始化值”;将tensorflow代码包装到python函数时出错,python,tensorflow,Python,Tensorflow,错误是“试图使用未初始化的值状态变量”。但是我认为这段代码应该初始化这个值 这是我的代码,谢谢你: import tensorflow as tf def index(): state = tf.Variable(0, name="state_variable") new_value = tf.add(state, tf.constant(1)) update = tf.assign(state, new_value) return update if __n
import tensorflow as tf
def index():
state = tf.Variable(0, name="state_variable")
new_value = tf.add(state, tf.constant(1))
update = tf.assign(state, new_value)
return update
if __name__ == "__main__":
with tf.Session() as sess:
init_op = tf.group(tf.local_variables_initializer(),
tf.global_variables_initializer())
op = index()
sess.run(init_op)
for _ in range(4):
print(sess.run(op))
您需要使用
tf.group
将op=index()
行放在定义init\u op
的行之前。当前,当您调用tf.group
时,tf.Variable(0,name=“state_Variable”)
尚未被调用,因此tf.group
不知道将其初始化放入init_op
。以下版本在我的计算机上运行正常:
import tensorflow as tf
def index():
state = tf.Variable(0, name="state_variable")
new_value = tf.add(state, tf.constant(1))
update = tf.assign(state, new_value)
return update
if __name__ == "__main__":
with tf.Session() as sess:
op = index()
init_op = tf.group(tf.local_variables_initializer(),
tf.global_variables_initializer())
sess.run(init_op)
for _ in range(4):
print(sess.run(op))
您需要使用
tf.group
将op=index()
行放在定义init\u op
的行之前。当前,当您调用tf.group
时,tf.Variable(0,name=“state_Variable”)
尚未被调用,因此tf.group
不知道将其初始化放入init_op
。以下版本在我的计算机上运行正常:
import tensorflow as tf
def index():
state = tf.Variable(0, name="state_variable")
new_value = tf.add(state, tf.constant(1))
update = tf.assign(state, new_value)
return update
if __name__ == "__main__":
with tf.Session() as sess:
op = index()
init_op = tf.group(tf.local_variables_initializer(),
tf.global_variables_initializer())
sess.run(init_op)
for _ in range(4):
print(sess.run(op))