先看看这个,知道使用目的:
http://www.tensorfly.cn/tfdoc/how_tos/summaries_and_tensorboard.html
然后上代码:
import tensorflow as tf
from tensorflow.examples.tutorials.mnist import input_data
from tensorflow.contrib.tensorboard.plugins import projector
#载入数据集
mnist = input_data.read_data_sets("MNIST_data/",one_hot=True)
#运行次数
max_steps = 1001
#图片数量
image_num = 3000
#文件路径
DIR = "/Users/yyzanll/Desktop/my_tensorflow/"
#定义会话
sess = tf.Session()
#载入图片
embedding = tf.Variable(tf.stack(mnist.test.images[:image_num]), trainable=False, name='embedding')
#参数概要
def variable_summaries(var):
with tf.name_scope('summaries'):
mean = tf.reduce_mean(var)
tf.summary.scalar('mean', mean)#平均值
with tf.name_scope('stddev'):
stddev = tf.sqrt(tf.reduce_mean(tf.square(var - 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)#直方图
#命名空间
with tf.name_scope('input'):
#这里的none表示第一个维度可以是任意的长度
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'):
image_shaped_input = tf.reshape(x, [-1, 28, 28, 1])
tf.summary.image('input', image_shaped_input, 10)
with tf.name_scope('layer'):
#创建一个简单神经网络
with tf.name_scope('weights'):
W = tf.Variable(tf.zeros([784,10]),name='W')
variable_summaries(W)
with tf.name_scope('biases'):
b = tf.Variable(tf.zeros([10]),name='b')
variable_summaries(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.nn.softmax_cross_entropy_with_logits(labels=y,logits=prediction))
tf.summary.scalar('loss',loss)
with tf.name_scope('train'):
#使用梯度下降法
train_step = tf.train.GradientDescentOptimizer(0.5).minimize(loss)
#初始化变量
sess.run(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))#把correct_prediction变为float32类型
tf.summary.scalar('accuracy',accuracy)
#产生metadata文件
if tf.gfile.Exists(DIR + 'projector/projector/metadata.tsv'):
tf.gfile.DeleteRecursively(DIR + 'projector/projector/metadata.tsv')
with open(DIR + 'projector/projector/metadata.tsv', 'w') as f:
labels = sess.run(tf.argmax(mnist.test.labels[:],1))
for i in range(image_num):
f.write(str(labels[i]) + '\n')
#合并所有的summary
merged = tf.summary.merge_all()
projector_writer = tf.summary.FileWriter(DIR + 'projector/projector',sess.graph)
saver = tf.train.Saver()
config = projector.ProjectorConfig()
embed = config.embeddings.add()
embed.tensor_name = embedding.name
embed.metadata_path = DIR + 'projector/projector/metadata.tsv'
embed.sprite.image_path = DIR + 'projector/data/mnist_10k_sprite.png'
embed.sprite.single_image_dim.extend([28,28])
projector.visualize_embeddings(projector_writer,config)
for i in range(max_steps):
#每个批次100个样本
batch_xs,batch_ys = mnist.train.next_batch(100)
run_options = tf.RunOptions(trace_level=tf.RunOptions.FULL_TRACE)
run_metadata = tf.RunMetadata()
summary,_ = sess.run([merged,train_step],feed_dict={x:batch_xs,y:batch_ys},options=run_options,run_metadata=run_metadata)
projector_writer.add_run_metadata(run_metadata, 'step%03d' % i)
projector_writer.add_summary(summary, i)
if i%100 == 0:
acc = sess.run(accuracy,feed_dict={x:mnist.test.images,y:mnist.test.labels})
print ("Iter " + str(i) + ", Testing Accuracy= " + str(acc))
saver.save(sess, DIR + 'projector/projector/a_model.ckpt', global_step=max_steps)
projector_writer.close()
sess.close()
我遇到报错:
InvalidArgumentError: You must feed a value for placeholder tensor ‘inputs/x_input’ with dtype float
我就把/Users/yyzanll/Desktop/my_tensorflow/projector/projector路径下的内容全部删了,重新跑。
然后打开终端
yyzanlldeMacBook-Pro:~ yyzanll$ cd /Users/yyzanll/Desktop/my_tensorflow/projector/projector
yyzanlldeMacBook-Pro:projector yyzanll$ tensorboard --logdir=/Users/yyzanll/Desktop/my_tensorflow/projector/projector
/Library/Python/2.7/site-packages/h5py/__init__.py:36: FutureWarning: Conversion of the second argument of issubdtype from `float` to `np.floating` is deprecated. In future, it will be treated as `np.float64 == np.dtype(float).type`.
from ._conv import register_converters as _register_converters
Starting TensorBoard 47 at http://0.0.0.0:6006
上面有Summary,想知道Summary是干嘛的?
Summary
Summary被收集在名为tf.GraphKeys.SUMMARIES的colletion中,Summary是对网络中Tensor取值进行监测的一种Operation。这些操作在图中是“外围”操作,不影响数据流本身。
网上抄个例子:
# 迭代的计数器
global_step = tf.Variable(0, trainable=False)
# 迭代的+1操作
increment_op = tf.assign_add(global_step, tf.constant(1))
# 实例应用中,+1操作往往在`tf.train.Optimizer.apply_gradients`内部完成。
# 创建一个根据计数器衰减的Tensor
lr = tf.train.exponential_decay(0.1, global_step, decay_steps=1, decay_rate=0.9, staircase=False)
# 把Tensor添加到观测中
tf.scalar_summary('learning_rate', lr)
# 并获取所有监测的操作`sum_opts`
sum_ops = tf.merge_all_summaries()
# 初始化sess
sess = tf.Session()
init = tf.initialize_all_variables()
sess.run(init) # 在这里global_step被赋初值
# 指定监测结果输出目录
summary_writer = tf.train.SummaryWriter('/tmp/log/', sess.graph)
# 启动迭代
for step in range(0, 10):
s_val = sess.run(sum_ops) # 获取serialized监测结果:bytes类型的字符串
summary_writer.add_summary(s_val, global_step=step) # 写入文件
sess.run(increment_op) # 计数器+1
调用tf.scalar_summary系列函数时,就会向默认的collection中添加一个Operation。
再次回顾“零存整取”原则:创建网络的各个层次都可以添加监测;在添加完所有监测,初始化sess之前,统一用tf.merge_all_summaries获取。
SummaryWriter文件中存储的是序列化的结果,需要借助TensorBoard才能查看。
在命令行中运行tensorboard,传入存储SummaryWriter文件的目录:
tensorboard --logdir /tmp/log
自定义collection
除了默认的集合,我们也可以自己创造collection组织对象。网络损失就是一类适宜对象。
tensorflow中的Loss提供了许多创建损失Tensor的方式。
x1 = tf.constant(1.0)
l1 = tf.nn.l2_loss(x1)
x2 = tf.constant([2.5, -0.3])
l2 = tf.nn.l2_loss(x2)
创建损失不会自动添加到集合中,需要手工指定一个collection:
tf.add_to_collection("losses", l1)
tf.add_to_collection("losses", l2)
创建完成后,可以统一获取所有损失,losses是个Tensor类型的list:
losses = tf.get_collection('losses')
另一种常见操作把所有损失累加起来得到一个Tensor:
loss_total = tf.add_n(losses)
执行操作可以得到损失取值:
sess = tf.Session()
init = tf.initialize_all_variables()
sess.run(init)
losses_val = sess.run(losses)
loss_total_val = sess.run(loss_total)