炼数成金Tensorflow学习笔记之5.3_tensorboard网络运行

炼数成金Tensorflow学习笔记之5.3_tensorboard网络运行

代码及分析

# -*- coding: utf-8 -*-
"""
Created on Fri Mar 27 18:20:16 2020

@author: 寒火qwer
"""

import tensorflow as tf
from tensorflow.examples.tutorials.mnist import input_data

tf.reset_default_graph()

# 载入数据集
mnist = input_data.read_data_sets('.\MNIST_data', one_hot=True)

# 参数概要
def variable_summary(var):
    with tf.name_scope('summary'):
        with tf.name_scope('mean'):
            mean = tf.reduce_mean(var)
        with tf.name_scope('stddev'):
            # 这里试一下直接用另一个命名空间中的值可不可以
            stddev = tf.sqrt(tf.reduce_mean(tf.square(var - mean)))
        tf.summary.scalar('mean', mean)  # 均值   
        tf.summary.scalar('stddev', stddev)  # 标准差   
        tf.summary.scalar('max', tf.reduce_max(var))  # 最大值 
        tf.summary.scalar('min', tf.reduce_min(var))  # 最小值
        tf.summary.histogram('histogram', var)  # 直方图
        

# 每个批次的大小
batch_size = 100
# 计算一共有多少个批次
n_batch = mnist.train.num_examples // batch_size

# 命名空间
with tf.name_scope('input'):
    # 定义两个placeholder
    x = tf.placeholder(tf.float32, [None, 784], name='x_input')
    y = tf.placeholder(tf.float32, [None, 10], name='y_input')

# 创建一个简单的神经网络
with tf.name_scope('layer'):
    with tf.name_scope('weight'):
        w = tf.Variable(tf.zeros([784,10]), name='w')
        variable_summary(w)
    with tf.name_scope('biases'):
        b = tf.Variable(tf.zeros([10]), name='b')
        variable_summary(b)
    with tf.name_scope('wx_plus_b'):
        wx_plus_b = tf.matmul(x,w) + b
    with tf.name_scope('softmax'):
        prediction = tf.nn.softmax(wx_plus_b)

# 二次代价函数
with tf.name_scope('loss'):
    loss = tf.reduce_mean(tf.square(y - prediction))
    tf.summary.scalar('loss', loss)
# 使用梯度下降法
with tf.name_scope('train'):
    train_op = tf.train.GradientDescentOptimizer(0.2).minimize(loss)

init_op = tf.global_variables_initializer()

# 求准确率
with tf.name_scope('acc'):
    with tf.name_scope('correct_prediction'):
        correct_prediction = tf.equal(tf.argmax(y, 1), tf.argmax(prediction, 1))
    with tf.name_scope('accuracy'):
        accuracy = tf.reduce_mean(tf.cast(correct_prediction, tf.float32))
        tf.summary.scalar('accuracy', accuracy)

# 合并所有的summary
merge = tf.summary.merge_all()


with tf.Session() as sess:
    sess.run(init_op)
    writer = tf.summary.FileWriter('E:/logs', sess.graph)
    for epoch in range(51):
        for batch in range(n_batch):
            batch_x, batch_y = mnist.train.next_batch(batch_size)
            summary, _ = sess.run([merge, train_op], feed_dict={x:batch_x, y:batch_y})
            writer.add_summary(summary, epoch*n_batch+batch)
            
        #writer.add_summary(summary, epoch)    
            
        acc = sess.run(accuracy, feed_dict= {x:mnist.test.images, y:mnist.test.labels})
        print("iter" + str(epoch) + ", testing acc: " + str(acc))
  1. tf.summary.scalar(name, values, collections=None)
    作用:记录标量统计结果
    name:结点名称,也将作为在tensorboard中的一个系列名称;
    values:需要记录的张量;
    collections=None:graph collections的关键字的可选列表。新的汇总op被添加到这些集合中。默认为[GraphKeys.SUMMARIES]。
  2. tf.summary.histogram(name, values, collections=None)
    作用:一般用来显示训练过程中变量的分布情况
    name:结点名称,也将作为在tensorboard中的一个系列名称;
    values:需要记录的张量;
    collections=None:graph collections的关键字的可选列表。新的汇总op被添加到这些集合中。默认为[GraphKeys.SUMMARIES]。
  3. tf.summary.merge_all(key=tf.GraphKeys.SUMMARIES, scope=None, name=None)
    作用:将所有summary全部保存到磁盘,以便tensorboard显示。如果没有特殊要求,一般用这一句就可一显示训练时的各种信息了。
    key=tf.GraphKeys.SUMMARIES:用于收集summary的GraphKey。默认为GraphKeys.SUMMARIES
    scope=None:用于筛选summary的可选范围
    **牢记:**tf.summary.merge_all得到的是一个节点,必须先传入session.run()运行才能获得真正的汇总!得到真正的汇总之后,调用tf.summary.FileWriter的add_summary()方法将训练过程数据保存在filewriter指定的文件中
  4. tf.summary.image(name, tensor, max_outputs=3, collections=None)
    作用:记录图像(构建的图像的Tensor必须是4-D形状[batch_size, height, width, channels])
    name:生成的节点的名称。也将作为TensorBoard中的系列名称。
    tensor:uint8或者float32型的4-D Tensor[batch_size, height, width, channels],其中channels为1, 3 或者4。
    max_outpus:要生成图像的最大批处理元素数。
    collections:ops.GraphKeys的可选列表。要添加摘要的集合。默认为[_ops.GraphKeys.SUMMARIES]。
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值