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调用另一个py文件并传递参数常见的方法及其应用场景

《Python调用另一个py文件并传递参数常见的方法及其应用场景》:本文主要介绍在Python中调用另一个py文件并传递参数的几种常见方法,包括使用import语句、exec函数、subproce... 目录前言1. 使用import语句1.1 基本用法1.2 导入特定函数1.3 处理文件路径2. 使用ex

Python中的可视化设计与UI界面实现

《Python中的可视化设计与UI界面实现》本文介绍了如何使用Python创建用户界面(UI),包括使用Tkinter、PyQt、Kivy等库进行基本窗口、动态图表和动画效果的实现,通过示例代码,展示... 目录从像素到界面:python带你玩转UI设计示例:使用Tkinter创建一个简单的窗口绘图魔法:用

HarmonyOS学习(七)——UI(五)常用布局总结

自适应布局 1.1、线性布局(LinearLayout) 通过线性容器Row和Column实现线性布局。Column容器内的子组件按照垂直方向排列,Row组件中的子组件按照水平方向排列。 属性说明space通过space参数设置主轴上子组件的间距,达到各子组件在排列上的等间距效果alignItems设置子组件在交叉轴上的对齐方式,且在各类尺寸屏幕上表现一致,其中交叉轴为垂直时,取值为Vert

Ilya-AI分享的他在OpenAI学习到的15个提示工程技巧

Ilya(不是本人,claude AI)在社交媒体上分享了他在OpenAI学习到的15个Prompt撰写技巧。 以下是详细的内容: 提示精确化:在编写提示时,力求表达清晰准确。清楚地阐述任务需求和概念定义至关重要。例:不用"分析文本",而用"判断这段话的情感倾向:积极、消极还是中性"。 快速迭代:善于快速连续调整提示。熟练的提示工程师能够灵活地进行多轮优化。例:从"总结文章"到"用

python: 多模块(.py)中全局变量的导入

文章目录 global关键字可变类型和不可变类型数据的内存地址单模块(单个py文件)的全局变量示例总结 多模块(多个py文件)的全局变量from x import x导入全局变量示例 import x导入全局变量示例 总结 global关键字 global 的作用范围是模块(.py)级别: 当你在一个模块(文件)中使用 global 声明变量时,这个变量只在该模块的全局命名空

【前端学习】AntV G6-08 深入图形与图形分组、自定义节点、节点动画(下)

【课程链接】 AntV G6:深入图形与图形分组、自定义节点、节点动画(下)_哔哩哔哩_bilibili 本章十吾老师讲解了一个复杂的自定义节点中,应该怎样去计算和绘制图形,如何给一个图形制作不间断的动画,以及在鼠标事件之后产生动画。(有点难,需要好好理解) <!DOCTYPE html><html><head><meta charset="UTF-8"><title>06

学习hash总结

2014/1/29/   最近刚开始学hash,名字很陌生,但是hash的思想却很熟悉,以前早就做过此类的题,但是不知道这就是hash思想而已,说白了hash就是一个映射,往往灵活利用数组的下标来实现算法,hash的作用:1、判重;2、统计次数;

零基础学习Redis(10) -- zset类型命令使用

zset是有序集合,内部除了存储元素外,还会存储一个score,存储在zset中的元素会按照score的大小升序排列,不同元素的score可以重复,score相同的元素会按照元素的字典序排列。 1. zset常用命令 1.1 zadd  zadd key [NX | XX] [GT | LT]   [CH] [INCR] score member [score member ...]

【机器学习】高斯过程的基本概念和应用领域以及在python中的实例

引言 高斯过程(Gaussian Process,简称GP)是一种概率模型,用于描述一组随机变量的联合概率分布,其中任何一个有限维度的子集都具有高斯分布 文章目录 引言一、高斯过程1.1 基本定义1.1.1 随机过程1.1.2 高斯分布 1.2 高斯过程的特性1.2.1 联合高斯性1.2.2 均值函数1.2.3 协方差函数(或核函数) 1.3 核函数1.4 高斯过程回归(Gauss

【学习笔记】 陈强-机器学习-Python-Ch15 人工神经网络(1)sklearn

系列文章目录 监督学习:参数方法 【学习笔记】 陈强-机器学习-Python-Ch4 线性回归 【学习笔记】 陈强-机器学习-Python-Ch5 逻辑回归 【课后题练习】 陈强-机器学习-Python-Ch5 逻辑回归(SAheart.csv) 【学习笔记】 陈强-机器学习-Python-Ch6 多项逻辑回归 【学习笔记 及 课后题练习】 陈强-机器学习-Python-Ch7 判别分析 【学