tensorflow数据流图

tensorflow数据流图`

import os
os.environ['TF_CPP_MIN_LOG_LEVEL']='2'
import tensorflow as tf
graph=tf.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")
    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"):
        # 用最新的输出更新Variables对象total_output
        update_total = total_output.assign_add(output)
        # 将前面的Variables对象global_step增1,只要数据流图运行,该操作便需要进行
        increment_step = global_step.assign_add(1)
    with tf.name_scope("summaries"):
        #cast()函数:数据类型转换
        avg = tf.div(update_total, tf.cast(increment_step, tf.float32),
                     name="average")
        # 为输出节点创建汇总数据
        tf.summary.scalar('output', output)
        tf.summary.scalar('sum of outputs over time', update_total)
        tf.summary.scalar('Average of outputs over time',avg)
    with tf.name_scope("global_ops"):
        # 初始化op
        init = tf.global_variables_initializer()
        # 将所有汇总数据合并到一个op中
        merged_summaries = tf.summary.merge_all()

sess = tf.Session(graph=graph)
writer = tf.summary.FileWriter("./improved_graph", graph)
sess.run(init)


def run_graph(input_tensor):
    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 the graph with various inputs
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.close()
sess.close()
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值