我试图了解如何为张量板收集摘要,并编写了一个简单的代码将x从1递增到5。
由于某些未知原因,我在所有步骤中都将变量My_x视为0。
import tensorflow as tf
tf.reset_default_graph() # To clear the defined variables/operations
# create the scalar variable
x = tf.Variable(0, name='x')
# ____step 1:____ create the scalar summary
x_summ = tf.summary.scalar(name='My_x', tensor=x)
# accumulate all summaries
merged_summary = tf.summary.merge_all()
# create the op for initializing all variables
model = tf.global_variables_initializer()
# launch the graph in a session
with tf.Session() as session:
# ____step 2:____ creating the writer inside the session
summary_writer = tf.summary.FileWriter('output', session.graph)
for i in range(5):
#initialize variables
session.run(model)
x = x + 1
# ____step 3:____ evaluate the scalar summary
merged_summary_ans, x_summ_ans, x_ans = session.run([merged_summary, x_summ, x])
print(x_ans)
print(x_summ_ans)
print(merged_summary_ans)
# ____step 4:____ add the summary to the writer (i.e. to the event file)
summary_writer.add_summary(summary=x_summ_ans, global_step=i)
summary_writer.flush()
summary_writer.close()
print('Done with writing the scalar summary')
答案 0 :(得分:2)
我可以在您的代码中看到两个问题:
1)首先是在每个循环中,您都在重新初始化全局变量。这会将x重置为其原始值(0)。
2)第二,当您更新x时,您正在使用TensorFlow加法操作覆盖到变量的链接。您增加x的代码用tf.add操作替换了'x',然后您的汇总值不再跟踪tf.Variable而是一个加法操作。如果在定义后添加“ print(x)”并使其在每个循环中运行一次,您将看到它最初以<tf.Variable 'x:0' shape=() dtype=int32_ref>
开始,但随后看到“ x = x + 1”然后打印(x)变成Tensor("add:0", shape=(), dtype=int32)
。在这里,您可以看到tf.summary.scalar仅与原始值兼容,并且可以看到为什么无法更新它。
这是我更改的代码,以使其正常工作,因此您可以在Tensorboard中看到x的线性值。
import tensorflow as tf
tf.reset_default_graph()
x = tf.Variable(0, name='x')
x_summary = tf.summary.scalar('x_', x)
init = tf.global_variables_initializer()
with tf.Session() as session:
session.run(init)
merged_summary_op = tf.summary.merge_all()
summary_writer = tf.summary.FileWriter('output', session.graph)
for i in range(5):
print(x.eval())
summary = session.run(merged_summary_op)
summary_writer.add_summary(summary, i)
session.run(tf.assign(x, x+1))
summary_writer.flush()
summary_writer.close()