本文主要是介绍Tensorboard学习——mnist_with_summaries.py ---- TensorFlow可视化,希望对大家解决编程问题提供一定的参考价值,需要的开发者们随着小编来一起学习吧!
mnist_with_summaries.py如下:
# Copyright 2015 Google Inc. All Rights Reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
# =============================================================================="""A very simple MNIST classifier, modified to display data in TensorBoard.See extensive documentation for the original model at
http://tensorflow.org/tutorials/mnist/beginners/index.mdSee documentation on the TensorBoard specific pieces at
http://tensorflow.org/how_tos/summaries_and_tensorboard/index.mdIf you modify this file, please update the exerpt in
how_tos/summaries_and_tensorboard/index.md."""
from __future__ import absolute_import
from __future__ import division
from __future__ import print_functionimport tensorflow.python.platform
#from tensorflow.examples.tutorials.mnist import input_data
import input_data
import tensorflow as tfflags = tf.app.flags
FLAGS = flags.FLAGS
flags.DEFINE_boolean('fake_data', False, 'If true, uses fake data ''for unit testing.')
flags.DEFINE_integer('max_steps', 1000, 'Number of steps to run trainer.')
flags.DEFINE_float('learning_rate', 0.01, 'Initial learning rate.')def main(_):# Import datamnist = input_data.read_data_sets('Mnist_data/', one_hot=True,fake_data=FLAGS.fake_data)sess = tf.InteractiveSession()# Create the modelx = tf.placeholder(tf.float32, [None, 784], name='x-input')W = tf.Variable(tf.zeros([784, 10]), name='weights')b = tf.Variable(tf.zeros([10], name='bias'))# Use a name scope to organize nodes in the graph visualizerwith tf.name_scope('Wx_b'):y = tf.nn.softmax(tf.matmul(x, W) + b)# Add summary ops to collect data_ = tf.histogram_summary('weights', W)_ = tf.histogram_summary('biases', b)_ = tf.histogram_summary('y', y)# Define loss and optimizery_ = tf.placeholder(tf.float32, [None, 10], name='y-input')# More name scopes will clean up the graph representationwith tf.name_scope('xent'):cross_entropy = -tf.reduce_sum(y_ * tf.log(y))_ = tf.scalar_summary('cross entropy', cross_entropy)with tf.name_scope('train'):train_step = tf.train.GradientDescentOptimizer(FLAGS.learning_rate).minimize(cross_entropy)with tf.name_scope('test'):correct_prediction = tf.equal(tf.argmax(y, 1), tf.argmax(y_, 1))accuracy = tf.reduce_mean(tf.cast(correct_prediction, tf.float32))_ = tf.scalar_summary('accuracy', accuracy)# Merge all the summaries and write them out to /tmp/mnist_logsmerged = tf.merge_all_summaries()writer = tf.train.SummaryWriter('/tmp/mnist_logs', sess.graph_def)tf.initialize_all_variables().run()# Train the model, and feed in test data and record summaries every 10 stepsfor i in range(FLAGS.max_steps):if i % 10 == 0: # Record summary data and the accuracyif FLAGS.fake_data:batch_xs, batch_ys = mnist.train.next_batch(100, fake_data=FLAGS.fake_data)feed = {x: batch_xs, y_: batch_ys}else:feed = {x: mnist.test.images, y_: mnist.test.labels}result = sess.run([merged, accuracy], feed_dict=feed)summary_str = result[0]acc = result[1]writer.add_summary(summary_str, i)print('Accuracy at step %s: %s' % (i, acc))else:batch_xs, batch_ys = mnist.train.next_batch(100, fake_data=FLAGS.fake_data)feed = {x: batch_xs, y_: batch_ys}sess.run(train_step, feed_dict=feed)if __name__ == '__main__':tf.app.run()
运行报错,大部分是Api版本问题:
根据提示错误选择相应部分修改。
AttributeError: 'module' object has no attribute 'SummaryWriter'
tf.train.SummaryWriter改为:tf.summary.FileWriter
AttributeError: 'module' object has no attribute 'summaries'
tf.merge_all_summaries()改为:summary_op = tf.summaries.merge_all()
tf.histogram_summary(var.op.name, var)
AttributeError: 'module' object has no attribute 'histogram_summary'
改为: tf.summaries.histogram()
tf.scalar_summary(l.op.name + ' (raw)', l)
AttributeError: 'module' object has no attribute 'scalar_summary'
tf.scalar_summary('images', images)改为:tf.summary.scalar('images', images)
tf.image_summary('images', images)改为:tf.summary.image('images', images)
ValueError: Only call `softmax_cross_entropy_with_logits` with named arguments (labels=..., logits=..., ...)
cifar10.loss(labels, logits) 改为:cifar10.loss(logits=logits, labels=labels)
cross_entropy = tf.nn.softmax_cross_entropy_with_logits(
logits, dense_labels, name='cross_entropy_per_example')
改为:
cross_entropy = tf.nn.softmax_cross_entropy_with_logits(
logits=logits, labels=dense_labels, name='cross_entropy_per_example')
TypeError: Using a `tf.Tensor` as a Python `bool` is not allowed. Use `if t is not None:` instead of `if t:` to test if a tensor is defined, and use TensorFlow ops such as tf.cond to execute subgraphs conditioned on the value of a tensor.
if grad: 改为 if grad is not None:
ValueError: Shapes (2, 128, 1) and () are incompatible
concated = tf.concat(1, [indices, sparse_labels])改为:
concated = tf.concat([indices, sparse_labels], 1)
-----可视化步骤-----
**`mnist_with_summaries.py`**主要提供了一种在Tensorboard可视化方法,首先,编译运行代码:
运行完毕后,打开终端`Terminal`,输入`tensorboard --logdir=/tmp/mnist_logs`,就会运行出:`Starting TensorBoard on port 6006 (You can navigate to http://localhost:6006)`
然后,打开浏览器,输入链接`http://localhost:6006`:
其中,有一些选项,例如菜单栏里包括`EVENTS, IMAGES, GRAPH, HISTOGRAMS`,都可以一一点开查看~
另外,此时如果不关闭该终端,是无法在其他终端中重新生成可视化结果的,会出现端口占用的错误。
图形化相关链接:http://www.2cto.com/kf/201602/490107.html
http://wiki.jikexueyuan.com/project/tensorflow-zh/tutorials/mnist_tf.html
这篇关于Tensorboard学习——mnist_with_summaries.py ---- TensorFlow可视化的文章就介绍到这儿,希望我们推荐的文章对编程师们有所帮助!