使用tensorboard查看mnist数据集的图片内容

本文介绍了使用tensorboard查看mnist数据集的方法。参考《深入理解TensorFlow架构设计与实现原理》文章的最后,附完整代码
先展示一下显示效果:
在这里插入图片描述
首先读入数据集

mnist = input_data.read_data_sets('data/mnist', one_hot=True)

定义输入的变量

with tf.name_scope('input'):
    x = tf.placeholder(tf.float32, [None, 784], name='x-input')
    y_= tf.placeholder(tf.float32, [None, 10], name='y-input')

汇总图像信息
注意,这里的tf.summary.image传入3个参数,第一参数是它的名字,第二个参数是我们要处理的变量,这里的格式是[batch_size, height, weight, channels] 他们四个的含义分别表示数据的个数、图片的高度、图片的宽度、图片的通道数。其中需要说明的是batch_size和channels,batch_size为-1表示的是图片的个数不定,channels是图片的通道个数,它可以取3个值,分别是1、3、4,1表示的是灰度图片,3表示的是彩色图片(RGB),4表示的是带透明的彩色图片(RGBA),在这里,因为mnist数据集是灰度图片,所以设置为1。

with tf.name_scope('input_reshape'):
    # 将图像x转换为四阶张量
    image_shaped_input = tf.reshape(x, [-1, 28, 28, 1])
    # 添加汇总操作
    tf.summary.image('input', image_shaped_input, 10)

定义输入的数据集函数
这个函数的作用是通过bool值train来控制输入的数据集是训练集还是测试集。

def feed_dict(train):
    if train:
        xs, ys = mnist.train.next_batch(100, fake_data=False)
    else:
        xs, ys = mnist.test.images, mnist.test.labels
    return {x: xs, y_: ys}

聚集汇总操作
这一步的作用就是将代码中的tf.summary中的汇总聚集起来,放在merged变量中,可以一起操作。

merged = tf.summary.merge_all()

定义session并初始化变量
在这里定义的是一个交互式session

sess = tf.InteractiveSession()
tf.global_variables_initializer().run()

定义一个FileWriter

writer = tf.summary.FileWriter('graph', sess.graph)

将汇总信息写入writer
writer只是写入了我们的session中的图信息,而我们的汇总信息的信息还没有写入呢!

# 将汇总数据加入writer
summary = sess.run(merged, feed_dict=feed_dict(False))
writer.add_summary(summary)

执行writer等后续操作

sess.run(writer)
writer.close()
sess.close()

启动tensorboard

tensorboard --logdir=graph

完整代码

import tensorflow as tf 

from tensorflow.examples.tutorials.mnist import input_data

mnist = input_data.read_data_sets('data/mnist', one_hot=True)

with tf.name_scope('input'):
    x = tf.placeholder(tf.float32, [None, 784], name='x-input')
    y_= tf.placeholder(tf.float32, [None, 10], name='y-input')
with tf.name_scope('input_reshape'):
    # 将图像x转换为四阶张量
    image_shaped_input = tf.reshape(x, [-1, 28, 28, 1])
    # 添加汇总操作
    tf.summary.image('input', image_shaped_input, 10)

def feed_dict(train):
    if train:
        xs, ys = mnist.train.next_batch(100, fake_data=False)
    else:
        xs, ys = mnist.test.images, mnist.test.labels
    return {x: xs, y_: ys}

merged = tf.summary.merge_all()

sess = tf.InteractiveSession()
tf.global_variables_initializer().run()

writer = tf.summary.FileWriter('graph', sess.graph)
# 将汇总数据加入writer
summary = sess.run(merged, feed_dict=feed_dict(False))
writer.add_summary(summary)

sess.run(writer)
writer.close()
sess.close()


  • 2
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 1
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值