import tensorflow as tf
graph = tf.Graph()
arr = [i for i in range(20)]
with graph.as_default():
sess = tf.Session(graph=graph)
with tf.name_scope("variables"):
global_steps = tf.Variable(0, dtype=tf.int32, trainable=False, name="global_steps")
with tf.name_scope("input"):
a = tf.placeholder(tf.int32, shape=[], name="placeholder_a") #转化为张量
with tf.name_scope("update"):
increment_step = global_steps.assign_add(1)
#注意这里,summary.scaler接受的参数是标量,如果是一个张量数组或者带维度的张量,可以使用tf.reduce_sum()降维,变为标量
with tf.name_scope("summary"):
output = a
#output = tf.reduce_sum(a)
tf.summary.scalar("output", output)
with tf.name_scope("global_ops"):
init = tf.global_variables_initializer()
merged_summaries = tf.summary.merge_all()
writer = tf.summary.FileWriter("./train", sess.graph)
sess.run(init)
def run_graph(input_tensor):
feed_dict = {a: input_tensor} #字典的值可以使数字、字符串、列表、numpy,当shape=[],则为数字
step, summary = sess.run([increment_step, merged_summaries], feed_dict = feed_dict)
writer.add_summary(summary, global_step=step)
for i in range(len(arr)):
input_tensor = i
run_graph(input_tensor)
在代码中存在五个命名空间,但是显示时只有四个,我记得一种解释是tensorboard并不会将tf.summary显示出来,而在本模块并没有进行任何张量操作,所以不显示。
修改代码:
在summaries命名空间添加节点计算
import tensorflow as tf
graph = tf.Graph()
arr = [i for i in range(20)]
with graph.as_default():
sess = tf.Session(graph=graph)
with tf.name_scope("variables"):
global_steps = tf.Variable(0, dtype=tf.int32, trainable=False, name="global_steps")
with tf.name_scope("input"):
a = tf.placeholder(tf.int32, shape=[], name="placeholder_a")
with tf.name_scope("update"):
increment_step = global_steps.assign_add(1)
with tf.name_scope("summaries"):
b = tf.constant(dtype=tf.int32, shape=[], value=2)
output = a + b
#tf.summary.scalar("output", output)
tf.summary.scalar("output", a)
with tf.name_scope("global_ops"):
init = tf.global_variables_initializer()
merged_summaries = tf.summary.merge_all()
writer = tf.summary.FileWriter("./train", sess.graph)
sess.run(init)
def run_graph(input_tensor):
feed_dict = {a: input_tensor}
step, summary = sess.run([increment_step, merged_summaries], feed_dict = feed_dict)
writer.add_summary(summary, global_step=step)
for i in range(len(arr)):
input_tensor = i
run_graph(input_tensor)
则summaries可以显示出来。
对于像这种简单的不追求模型复用(呗做成模块来给其他人用),可以按照这种框架来进行搭建