Tensorboard学习——mnist_with_summaries.py ---- TensorFlow可视化

2024-05-04 00:18

本文主要是介绍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可视化的文章就介绍到这儿,希望我们推荐的文章对编程师们有所帮助!


原文地址:
本文来自互联网用户投稿,该文观点仅代表作者本人,不代表本站立场。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如若转载,请注明出处:http://www.chinasem.cn/article/957963

相关文章

8种快速易用的Python Matplotlib数据可视化方法汇总(附源码)

《8种快速易用的PythonMatplotlib数据可视化方法汇总(附源码)》你是否曾经面对一堆复杂的数据,却不知道如何让它们变得直观易懂?别慌,Python的Matplotlib库是你数据可视化的... 目录引言1. 折线图(Line Plot)——趋势分析2. 柱状图(Bar Chart)——对比分析3

使用Vue-ECharts实现数据可视化图表功能

《使用Vue-ECharts实现数据可视化图表功能》在前端开发中,经常会遇到需要展示数据可视化的需求,比如柱状图、折线图、饼图等,这类需求不仅要求我们准确地将数据呈现出来,还需要兼顾美观与交互体验,所... 目录前言为什么选择 vue-ECharts?1. 基于 ECharts,功能强大2. 更符合 Vue

重新对Java的类加载器的学习方式

《重新对Java的类加载器的学习方式》:本文主要介绍重新对Java的类加载器的学习方式,具有很好的参考价值,希望对大家有所帮助,如有错误或未考虑完全的地方,望不吝赐教... 目录1、介绍1.1、简介1.2、符号引用和直接引用1、符号引用2、直接引用3、符号转直接的过程2、加载流程3、类加载的分类3.1、显示

Git可视化管理工具(SourceTree)使用操作大全经典

《Git可视化管理工具(SourceTree)使用操作大全经典》本文详细介绍了SourceTree作为Git可视化管理工具的常用操作,包括连接远程仓库、添加SSH密钥、克隆仓库、设置默认项目目录、代码... 目录前言:连接Gitee or github,获取代码:在SourceTree中添加SSH密钥:Cl

Pandas中统计汇总可视化函数plot()的使用

《Pandas中统计汇总可视化函数plot()的使用》Pandas提供了许多强大的数据处理和分析功能,其中plot()函数就是其可视化功能的一个重要组成部分,本文主要介绍了Pandas中统计汇总可视化... 目录一、plot()函数简介二、plot()函数的基本用法三、plot()函数的参数详解四、使用pl

使用Python实现矢量路径的压缩、解压与可视化

《使用Python实现矢量路径的压缩、解压与可视化》在图形设计和Web开发中,矢量路径数据的高效存储与传输至关重要,本文将通过一个Python示例,展示如何将复杂的矢量路径命令序列压缩为JSON格式,... 目录引言核心功能概述1. 路径命令解析2. 路径数据压缩3. 路径数据解压4. 可视化代码实现详解1

Python 交互式可视化的利器Bokeh的使用

《Python交互式可视化的利器Bokeh的使用》Bokeh是一个专注于Web端交互式数据可视化的Python库,本文主要介绍了Python交互式可视化的利器Bokeh的使用,具有一定的参考价值,感... 目录1. Bokeh 简介1.1 为什么选择 Bokeh1.2 安装与环境配置2. Bokeh 基础2

Java学习手册之Filter和Listener使用方法

《Java学习手册之Filter和Listener使用方法》:本文主要介绍Java学习手册之Filter和Listener使用方法的相关资料,Filter是一种拦截器,可以在请求到达Servl... 目录一、Filter(过滤器)1. Filter 的工作原理2. Filter 的配置与使用二、Listen

一文带你搞懂Python中__init__.py到底是什么

《一文带你搞懂Python中__init__.py到底是什么》朋友们,今天我们来聊聊Python里一个低调却至关重要的文件——__init__.py,有些人可能听说过它是“包的标志”,也有人觉得它“没... 目录先搞懂 python 模块(module)Python 包(package)是啥?那么 __in

基于Python打造一个可视化FTP服务器

《基于Python打造一个可视化FTP服务器》在日常办公和团队协作中,文件共享是一个不可或缺的需求,所以本文将使用Python+Tkinter+pyftpdlib开发一款可视化FTP服务器,有需要的小... 目录1. 概述2. 功能介绍3. 如何使用4. 代码解析5. 运行效果6.相关源码7. 总结与展望1