Tensorboard的使用
1、添加命名空间
在之前的程序的基础上添加命名空间,这样就可以把一些操作打包在一起了,更加有利于我们的可视化(使结构图更加的简洁)
命名空间的语法:
with tf.name_scope('name') #name为我们给这个空间取的名字
记得给变量取变量名:
x = tf.placeholder(tf.float32, [None, 784])
x = tf.placeholder(tf.float32, [None, 784], name='x_input')
# 命名空间
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')
2、将得到的数据写入一个文件当中
第三行中,我们写了一个函数,用于将数据写入到指定的路径下。
with tf.Session() as sess: sess.run(init) writer = tf.summary.FileWriter('logs/', sess.graph) # 参数一为路劲,参数二为存放的结构
3、复制刚刚生成的文件的路劲
找到上一步(第二步)生成的文件,并复制该路劲
4、获取tensorboard的网址
打开命令行,输入如下代码
复制最后一行的IP地址到浏览器中打开,就可以得到可视化的tensorboard了。
注意:
在使用tensorboard的过程中,不可以将命令行的窗口给关了,或者结束操作,否则会出现下面的情况——无法访问此网站(路径要用全英文的,不然又可能加载不到数据)
1、程序完整结构:
图中:05/logs/events.out.tfevents.1524285137.ZL-WSJUN 为 生成的文件
图中:05/MINIST_data/tensorboard的使用 为代码文件
2、完整的代码:
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 # 命名空间 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') # 创建一个简单的神经网络 W = tf.Variable(tf.zeros([784, 10])) b = tf.Variable(tf.zeros([10])) prediction = tf.nn.softmax(tf.matmul(x, W) + b) # 二次代价函数 loss = tf.reduce_mean(tf.square(y - prediction)) # 使用梯度下降法 train_step = tf.train.GradientDescentOptimizer(0.2).minimize(loss) # 初始化变量 init = tf.global_variables_initializer() # 结果存放在一个布尔型列表中 correct_prediction = tf.equal(tf.argmax(y, 1), tf.argmax(prediction, 1)) # argmax返回一维张量中最大的值所在的位置 # 求准确率 accuracy = tf.reduce_mean(tf.cast(correct_prediction, tf.float32)) with tf.Session() as sess: sess.run(init) writer = tf.summary.FileWriter('logs/', sess.graph) # 第一个参数为路劲,第二个参数为存放的结构 for epoch in range(1): 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))