【TensorFlow】5 Tensorboard的简易使用

5-1 使用Tensorboard查看简单向量相加

import tensorflow as tf
input1=tf.constant([1.0,2.0],name="input1")
input2=tf.Variable(tf.random_uniform([2]),name="input2")
output= tf.add_n([input1,input2],name="add")

with  tf.Session() as sess:
    sess.run(tf.global_variables_initializer())
    writer=tf.summary.FileWriter("F:/logs4",sess.graph)
  1. 运行代码后,自动在"F:/logs6"位置生成用于tensorboard的显示信息。
  2. Windows下,在Anaconda Prompt,CMD中路径切换到保存的主硬盘, F: ,否则无法显示信息。
  3. 在CMD打开后输入以下命令:tensorboard --logdir  F:/logs4    (路径可变化,但不可含有中文字符)。
  4. 浏览器中输入提示网址打开tensorboard,得到计算图的可视化信息。

5-2 使用Tensorboard查看简单神经网络结构

 “为了更好组织可视化效果图中的计算节点,TensorFlow计算图同一个命名空间下的所有节点会被缩略成一个节点

  tf,variable_scope函数与tf.name_scope函数提供命名空间管理功能。”

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

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

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

#定义两个placeholder
with tf.name_scope("input"):
    x = tf.placeholder(tf.float32,[None,784],name="input_x")
    y = tf.placeholder(tf.float32,[None,10],name="input_y")
#创建一个简单的神经网络
with tf.name_scope("L1_weights"):
    with tf.name_scope("L1"):
        W = tf.Variable(tf.zeros([784,10]),name="L1_w1")
    with tf.name_scope("L1_bias"):
        b = tf.Variable(tf.zeros([10]),name="L1_b1")
    with tf.name_scope("L"):
        L1=tf.matmul(x,W)+b
    with tf.name_scope("softmax"):
        prediction = tf.nn.softmax(tf.nn.tanh(L1))

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

#初始化变量
init = tf.global_variables_initializer()

#结果存放在一个布尔型列表中
with tf.name_scope("accuracy"):
    with tf.name_scope("correct_prediction"):
        correct_prediction = tf.equal(tf.argmax(y,1),tf.argmax(prediction,1))#argmax返回一维张量中最大的值所在的位置
#求准确率
    with tf.name_scope("accuracy"):
        accuracy = tf.reduce_mean(tf.cast(correct_prediction,tf.float32))

with tf.Session() as sess:
    sess.run(init)
    writer=tf.summary.FileWriter("F:/logs6",sess.graph)
    for epoch in range(5):
        for batch in range(n_batch):
            batch_xs,batch_ys =  mnist.train.next_batch(batch_size)
            sess.run(train_step,feed_dict={x:batch_xs,y:batch_ys})
        
        acc = sess.run(accuracy,feed_dict={x:mnist.test.images,y:mnist.test.labels})
        print("Iter " + str(epoch) + ",Testing Accuracy " + str(acc))

5-3 使用Tensorboard绘制网络识别准确率(accuracy)和误差(loss)曲线

在5-2的基础上,添加下列代码,就能在tensorboard中绘制准确率和误差的曲线 

……
tf.summary.scalar("loss",loss)
……
tf.summary.scalar("accuracy",accuracy)
……
#合并所有的summary,方便后续运行显示
merged = tf.summary.merge_all()
……
with tf.Session() as sess:
……
    #要运行后才能记录accuracy和loss
    summary,_=sess.run([merged,train_step],feed_dict={x:batch_xs,y:batch_ys})
    writer.add_summary(summary,batch)

完整代码如下: 

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)

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

#定义两个placeholder
with tf.name_scope("input"):
    x = tf.placeholder(tf.float32,[None,784],name="input_x")
    y = tf.placeholder(tf.float32,[None,10],name="input_y")
#创建一个简单的神经网络
with tf.name_scope("L1_weights"):
    with tf.name_scope("L1"):
        W = tf.Variable(tf.zeros([784,10]),name="L1_w1")
    with tf.name_scope("L1_bias"):
        b = tf.Variable(tf.zeros([10]),name="L1_b1")
    with tf.name_scope("L"):
        L1=tf.matmul(x,W)+b
    with tf.name_scope("softmax"):
        prediction = tf.nn.softmax(tf.nn.tanh(L1))

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

#初始化变量
init = tf.global_variables_initializer()

#结果存放在一个布尔型列表中
with tf.name_scope("accuracy"):
    with tf.name_scope("correct_prediction"):
        correct_prediction = tf.equal(tf.argmax(y,1),tf.argmax(prediction,1))#argmax返回一维张量中最大的值所在的位置
#求准确率
    with tf.name_scope("accuracy"):
        accuracy = tf.reduce_mean(tf.cast(correct_prediction,tf.float32))
        tf.summary.scalar("accuracy",accuracy)

#合并所有的summary,方便后续运行
merged = tf.summary.merge_all()
        
with tf.Session() as sess:
    sess.run(init)
    writer=tf.summary.FileWriter("F:/logs8",sess.graph)

    for batch in range(20000):
        batch_xs,batch_ys =  mnist.train.next_batch(batch_size)
        summary,_=sess.run([merged,train_step],feed_dict={x:batch_xs,y:batch_ys})
        writer.add_summary(summary,batch)
    
        if batch %2000 ==0:
            acc = sess.run(accuracy,feed_dict={x:mnist.test.images,y:mnist.test.labels})
            print("Iter " + str(batch) + ",Testing Accuracy " + str(acc))

 【遇到问题】TensorBoard报错:InvalidArgumentError: You must feed a value for placeholder tensor 'inputs/x_input' wi(程序第一次运行正常,第二次报该错)

 解决办法:[参考链接]

#在代码前列加入此语句
tf.reset_default_graph()

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

曾小蛙

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值