gpt4 book ai didi

python - 尝试使用未初始化的变量 -tensorboard

转载 作者:行者123 更新时间:2023-12-01 08:51:00 26 4
gpt4 key购买 nike

我刚刚开始使用 Tensorboard,并想创建一个简单的示例,其中有一个调用函数的循环。在该函数内,我有一个张量变量,该变量加一,然后将其添加到摘要中。

我收到 FailedPreconditionError:尝试使用未初始化的值 x_scalar

但我以为我正在使用第 10 行和第 14 行初始化 x_scalar。初始化的正确方法是什么?

import tensorflow as tf
tf.reset_default_graph() # To clear the defined variables and operations of the previous cell

# create the scalar variable
x_scalar = tf.get_variable('x_scalar', shape=[], initializer=tf.truncated_normal_initializer(mean=0, stddev=1))

# ____step 1:____ create the scalar summary
first_summary = tf.summary.scalar(name='My_first_scalar_summary', tensor=x_scalar)
step = 1
init = tf.global_variables_initializer()
with tf.Session() as sess:
sess.run(init)
writer = tf.summary.FileWriter('./graphs', sess.graph)
sess.run(x_scalar.assign(1))
print(sess.run(x_scalar))
print("---------------------------")
def main():
global init
global first_summary
global step

# launch the graph in a session
# with tf.Session() as sess:
# # ____step 2:____ creating the writer inside the session
# writer = tf.summary.FileWriter('./graphs', sess.graph)
for s in range(100):
func()

def func():
global init
global first_summary
global step
global x_scalar

with tf.Session() as sess:
# ____step 2:____ creating the writer inside the session

# loop over several initializations of the variable
sess.run(x_scalar.assign(x_scalar + 1))
# ____step 3:____ evaluate the scalar summary
summary = sess.run(first_summary)
# ____step 4:____ add the summary to the writer (i.e. to the event file)
writer.add_summary(summary, step)
step = step + 1
print('Done with writing the scalar summary')
if __name__ == '__main__':
main()

最佳答案

您在不同的 tf.Session() 中初始化了变量。当使用 tf.Session() 作为上下文管理器时, session 会在代码块完成后自动关闭。

您可以使用检查点和元图来保存图+权重,然后将它们加载到新创建的 session 中。

或者您可以尝试传递 session

sess = tf.Session()
sess.run([CODE])
sess.run([CODE])
sess.run([CODE])
sess.run([CODE])
sess.close()

已编辑:进行了更正

关于python - 尝试使用未初始化的变量 -tensorboard,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53125097/

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