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

相关文章

Python中Tensorflow无法调用GPU问题的解决方法

《Python中Tensorflow无法调用GPU问题的解决方法》文章详解如何解决TensorFlow在Windows无法识别GPU的问题,需降级至2.10版本,安装匹配CUDA11.2和cuDNN... 当用以下代码查看GPU数量时,gpuspython返回的是一个空列表,说明tensorflow没有找到

Go学习记录之runtime包深入解析

《Go学习记录之runtime包深入解析》Go语言runtime包管理运行时环境,涵盖goroutine调度、内存分配、垃圾回收、类型信息等核心功能,:本文主要介绍Go学习记录之runtime包的... 目录前言:一、runtime包内容学习1、作用:① Goroutine和并发控制:② 垃圾回收:③ 栈和

Python数据分析与可视化的全面指南(从数据清洗到图表呈现)

《Python数据分析与可视化的全面指南(从数据清洗到图表呈现)》Python是数据分析与可视化领域中最受欢迎的编程语言之一,凭借其丰富的库和工具,Python能够帮助我们快速处理、分析数据并生成高质... 目录一、数据采集与初步探索二、数据清洗的七种武器1. 缺失值处理策略2. 异常值检测与修正3. 数据

Android学习总结之Java和kotlin区别超详细分析

《Android学习总结之Java和kotlin区别超详细分析》Java和Kotlin都是用于Android开发的编程语言,它们各自具有独特的特点和优势,:本文主要介绍Android学习总结之Ja... 目录一、空安全机制真题 1:Kotlin 如何解决 Java 的 NullPointerExceptio

使用Python和Matplotlib实现可视化字体轮廓(从路径数据到矢量图形)

《使用Python和Matplotlib实现可视化字体轮廓(从路径数据到矢量图形)》字体设计和矢量图形处理是编程中一个有趣且实用的领域,通过Python的matplotlib库,我们可以轻松将字体轮廓... 目录背景知识字体轮廓的表示实现步骤1. 安装依赖库2. 准备数据3. 解析路径指令4. 绘制图形关键

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