tensorboard
可视化的好帮手
with tf.name_scope('W'):
W = tf.Variable(tf.zeros([784, 10]) , name = 'W')
然后,我们需要把graph写到文件里面,通过tensorboard来调用显示
writer = tf.summary.FileWriter('logs' , sess.graph)
运行程序,会在logs文件夹中保存此次的events。
然后将shell定位到当前文件夹中执行:
tensorboard --logdir = logs
以前我们是复制这个网址在浏览器打开,但是我发现这个方式行不通了,不知道是我方法的问题,还是浏览器的问题,所以我们用另一种方式。
打开你的浏览器,输入localhost:6006,回车。这时tensorboard就在你的浏览器中启动了
2.histograms显示,scalars显示
在需要查看的变量下面加上:
#histograms
tf.summary.histogram('W' , W)
#scalars
tf.summary.scalar('loss' , cross_entropy)
summary_op = tf.summary.merge_all()
for i in range(1000):
batch_xs, batch_ys = mnist.train.next_batch(100)
summary_str = sess.run(summary_op , feed_dict={x:batch_xs , y_:batch_ys})
writer.add_summary(summary_str , i)
train_step.run({x: batch_xs, y_: batch_ys})
tensorboard --logdir=logs
这里有一点是要注意的就是,我的tensorboard是pip安装的,如果你的不是,那么tensorboard的启动方式变为
python tensorflow/tensorboard/tensorboard.py --logdir=path
并在浏览器中输出localhost:6006打开tensorboard查看:
最后贴上完整的代码(softmax分类mnist数据集):
"""A very simple MNIST classifier.
See extensive documentation at
http://tensorflow.org/tutorials/mnist/beginners/index.md
"""
from __future__ import absolute_import
from __future__ import division
from __future__ import print_function
# Import data
#from tensorflow.examples.tutorials.mnist import input_data
import input_data
import tensorflow as tf
mnist = input_data.read_data_sets("Mnist_data/", one_hot=True)
sess = tf.InteractiveSession()
# Create the model
x = tf.placeholder(tf.float32, [None, 784] , name = 'input_x')
W = tf.Variable(tf.zeros([784, 10]) , name = 'W')
tf.summary.histogram('W' , W)
b = tf.Variable(tf.zeros([10]) , name = 'b')
tf.summary.histogram('b' , b)
y = tf.nn.softmax(tf.matmul(x, W) + b , name = 'y_out')
# Define loss and optimizer
y_ = tf.placeholder(tf.float32, [None, 10] , name = 'input_y')
with tf.name_scope('loss'):
cross_entropy = -tf.reduce_sum(y_ * tf.log(y))
tf.summary.scalar('loss' , cross_entropy)
summary_op = tf.summary.merge_all()
writer = tf.summary.FileWriter('logs' , sess.graph)
train_step = tf.train.GradientDescentOptimizer(0.01).minimize(cross_entropy)
# Train
tf.initialize_all_variables().run()
for i in range(1000):
batch_xs, batch_ys = mnist.train.next_batch(100)
summary_str = sess.run(summary_op , feed_dict={x:batch_xs , y_:batch_ys})
writer.add_summary(summary_str , i)
train_step.run({x: batch_xs, y_: batch_ys})
# Test trained model
correct_prediction = tf.equal(tf.argmax(y, 1), tf.argmax(y_, 1))
accuracy = tf.reduce_mean(tf.cast(correct_prediction, tf.float32))
print(accuracy.eval({x: mnist.test.images, y_: mnist.test.labels}))