用tensorflow1.2.1版本调试出了一个小实例并用tensorboard查看graph以及summary

这几天在看面向机器智能的tensorflow实践这本教材,在第三章的最后有一个实例,我照着敲了代码看看结果,由于书本中用的是低版本的tensdoflow所以有些代码进行了修改,修改过程中踩了一些坑,最后还是调试出来了。

import tensorflow as tf

graph = tf.Graph()                   # 显式创建一个Graph对象
with graph.as_default():
    with tf.name_scope("variables"):
        # 追踪数据流程图运行次数的Variables对象
        global_step = tf.Variable(0, dtype=tf.int32, trainable=False, name="global_step")
        # 追踪所有输出随时间的累加和的Variables对象
        total_output = tf.Variable(0.0, dtype=tf.float32, trainable=False, name="total_output")

        # 主要变换的OP
    with tf.name_scope("transformation"):
        # 独立的输入层
        with tf.name_scope("input"):
            # 创建可接收一个向量的占位符
            a = tf.placeholder(tf.float32, shape=[None], name="input_placeholder_a")

        # 独立的中间层
        with tf.name_scope("intermediate_layer"):
            b = tf.reduce_prod(a, name="product_b")
            c = tf.reduce_sum(a, name="sum_c")

        # 独立的输出层
        with tf.name_scope("output"):
            output = tf.add(b, c, name="output")

    with tf.name_scope("update"):
        # 用最新的输出更新Variable对象total_output
        update_total = total_output.assign_add(output)
        # 将前面的Variable对象global_step增1,只要数据流程图运行,该操作便需要进行
        increment_step = global_step.assign_add(1)

    # 汇总OP
    with tf.name_scope("summaries"):
        avg = tf.div(update_total, tf.cast(increment_step, tf.float32), name="average")

        # 为输出节点创建汇总数据
        tf.summary.scalar('output_summary', output)
        tf.summary.scalar('total_summary', update_total)
        tf.summary.scalar('average_summary', avg)

    # 全局Variable对象和OP
    with tf.name_scope("global_ops"):
        # 初始化OP
        init = tf.global_variables_initializer()    # 已修改为最新函数
        # 将所有汇总数据合并到一个OP中
        merged_summaries = tf.summary.merge_all()

# 用明确创建的Graph对象启动一个会话
sess = tf.Session(graph=graph)
# 开启一个Summary.FileWriter对象,保存汇总数据
writer = tf.summary.FileWriter('tmp1', sess.graph)
# 初始化Variable对象
sess.run(init)


def run_graph(input_tensor):
    """
    辅助函数;用给定的输入张量运行数据流程图,
    并保存汇总数据
    :param input_tensor:
    :return:
    """
    feed_dict = {a: input_tensor}
    _, step, summary = sess.run([output, increment_step, merged_summaries], feed_dict=feed_dict)
    writer.add_summary(summary, global_step=step)

# 用不同的输入运行该数据流程图
run_graph([2, 8])
run_graph([3, 1, 3, 3])
run_graph([8])
run_graph([1, 2, 3])
run_graph([11, 4])
run_graph([4, 1])
run_graph([7, 3, 1])
run_graph([6, 3])
run_graph([0, 2])
run_graph([4, 5, 6])


# 将汇总数据写入磁盘
writer.flush()
# 关闭writer对象
writer.close()
# 关闭Session对象
sess.close()


运行完成后通过指令打开tensorboard,如图:






提示:summary界面默认不显示summary图(你可以看到summary最右边标了个3,代表有三张图),点击summary就能看到了(开始我以为自己代码有问题,半天没找到,原来需要点击下)。

猜你喜欢

转载自blog.csdn.net/qq_37541097/article/details/74389584
今日推荐