实验8-tensorboard

news/2024/9/21 20:34:55

VMware虚拟机 Ubuntu20-LTS

python3.6

tensorflow1.15.0

keras2.3.1

运行截图:

 

 

 

代码:

实验8-1tensorboard可视化

import tensorflow as tf#定义命名空间
with tf.name_scope('input'):#fetch:就是同时运行多个op的意思input1 = tf.constant(3.0,name='A')#定义名称,会在tensorboard中代替显示input2 = tf.constant(4.0,name='B')input3 = tf.constant(5.0,name='C')
with tf.name_scope('op'):#加法add = tf.add(input2,input3)#乘法mul = tf.multiply(input1,add)
with tf.Session() as ss:#默认在当前py目录下的logs文件夹,没有会自己创建result = ss.run([mul,add])wirter = tf.summary.FileWriter('logs/demo/',ss.graph)print(result)

 

实验8-2tensorboard案例

#!/usr/bin/env python
# -*- coding: utf-8 -*-
from __future__ import absolute_import
from __future__ import division
from __future__ import print_functionimport argparse
import sys
import os
import tensorflow as tffrom tensorflow.examples.tutorials.mnist import input_data
max_steps = 200  # 最大迭代次数 默认1000
learning_rate = 0.001   # 学习率
dropout = 0.9   # dropout时随机保留神经元的比例data_dir = os.path.join('data', 'mnist')# 样本数据存储的路径
if not os.path.exists('log'):os.mkdir('log')
log_dir = 'log'   # 输出日志保存的路径
mnist = input_data.read_data_sets("MNIST_data",one_hot=True)
sess = tf.InteractiveSession()with tf.name_scope('input'):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)def weight_variable(shape):"""Create a weight variable with appropriate initialization."""initial = tf.truncated_normal(shape, stddev=0.1)return tf.Variable(initial)def bias_variable(shape):"""Create a bias variable with appropriate initialization."""initial = tf.constant(0.1, shape=shape)return tf.Variable(initial)def variable_summaries(var):"""Attach a lot of summaries to a Tensor (for TensorBoard visualization)."""with tf.name_scope('summaries'):# 计算参数的均值,并使用tf.summary.scaler记录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.scaler记录记录下标准差,最大值,最小值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)
def nn_layer(input_tensor, input_dim, output_dim, layer_name, act=tf.nn.relu):"""Reusable code for making a simple neural net layer.
    It does a matrix multiply, bias add, and then uses relu to nonlinearize.It also sets up name scoping so that the resultant graph is easy to read,and adds a number of summary ops."""
    # 设置命名空间with tf.name_scope(layer_name):# 调用之前的方法初始化权重w,并且调用参数信息的记录方法,记录w的信息with tf.name_scope('weights'):weights = weight_variable([input_dim, output_dim])variable_summaries(weights)# 调用之前的方法初始化权重b,并且调用参数信息的记录方法,记录b的信息with tf.name_scope('biases'):biases = bias_variable([output_dim])variable_summaries(biases)# 执行wx+b的线性计算,并且用直方图记录下来with tf.name_scope('linear_compute'):preactivate = tf.matmul(input_tensor, weights) + biasestf.summary.histogram('linear', preactivate)# 将线性输出经过激励函数,并将输出也用直方图记录下来activations = act(preactivate, name='activation')tf.summary.histogram('activations', activations)# 返回激励层的最终输出return activationshidden1 = nn_layer(x, 784, 500, 'layer1')with tf.name_scope('dropout'):keep_prob = tf.placeholder(tf.float32)tf.summary.scalar('dropout_keep_probability', keep_prob)dropped = tf.nn.dropout(hidden1, keep_prob)y = nn_layer(dropped, 500, 10, 'layer2', act=tf.identity)
with tf.name_scope('loss'):# 计算交叉熵损失(每个样本都会有一个损失)diff = tf.nn.softmax_cross_entropy_with_logits(labels=y_, logits=y)with tf.name_scope('total'):# 计算所有样本交叉熵损失的均值cross_entropy = tf.reduce_mean(diff)tf.summary.scalar('loss', cross_entropy)with tf.name_scope('train'):train_step = tf.train.AdamOptimizer(learning_rate).minimize(cross_entropy)
with tf.name_scope('accuracy'):with tf.name_scope('correct_prediction'):# 分别将预测和真实的标签中取出最大值的索引,弱相同则返回1(true),不同则返回0(false)correct_prediction = tf.equal(tf.argmax(y, 1), tf.argmax(y_, 1))with tf.name_scope('accuracy'):# 求均值即为准确率accuracy = tf.reduce_mean(tf.cast(correct_prediction, tf.float32))tf.summary.scalar('accuracy', accuracy)
# summaries合并
merged = tf.summary.merge_all()
# 写到指定的磁盘路径中
#删除src路径下所有文件
def delete_file_folder(src):'''delete files and folders'''if os.path.isfile(src):try:os.remove(src)except:passelif os.path.isdir(src):for item in os.listdir(src):itemsrc=os.path.join(src,item)delete_file_folder(itemsrc) try:os.rmdir(src)except:pass
#删除之前生成的log
if os.path.exists(log_dir + '/train'):delete_file_folder(log_dir + '/train')
if os.path.exists(log_dir + '/test'):delete_file_folder(log_dir + '/test')
train_writer = tf.summary.FileWriter(log_dir + '/train', sess.graph)
test_writer = tf.summary.FileWriter(log_dir + '/test')# 运行初始化所有变量
tf.global_variables_initializer().run()def feed_dict(train):"""Make a TensorFlow feed_dict: maps data onto Tensor placeholders."""if train:xs, ys = mnist.train.next_batch(100)k = dropoutelse:xs, ys = mnist.test.images, mnist.test.labelsk = 1.0return {x: xs, y_: ys, keep_prob: k}for i in range(max_steps):if i % 10 == 0:  # 记录测试集的summary与accuracysummary, acc = sess.run([merged, accuracy], feed_dict=feed_dict(False))test_writer.add_summary(summary, i)print('Accuracy at step %s: %s' % (i, acc))else:  # 记录训练集的summaryif i % 100 == 99:  # Record execution statsrun_options = tf.RunOptions(trace_level=tf.RunOptions.FULL_TRACE)run_metadata = tf.RunMetadata()summary, _ = sess.run([merged, train_step],feed_dict=feed_dict(True),options=run_options,run_metadata=run_metadata)train_writer.add_run_metadata(run_metadata, 'step%03d' % i)train_writer.add_summary(summary, i)print('Adding run metadata for', i)else:  # Record a summarysummary, _ = sess.run([merged, train_step], feed_dict=feed_dict(True))train_writer.add_summary(summary, i)train_writer.close()
test_writer.close()

 

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

如若内容造成侵权/违法违规/事实不符,请联系我们进行投诉反馈,一经查实,立即删除!

相关文章

实验7-使用TensorFlow完成MNIST手写体识别

VMware虚拟机 Ubuntu20-LTS python3.6 tensorflow1.15.0 keras2.3.1 运行截图:代码:import os os.environ[TF_CPP_MIN_LOG_LEVEL]=2import numpy as np import tensorflow as tf from tensorflow_core.examples.tutorials.mnist import input_data import time #%% #使用tens…

C121 李超树+DP P4655 [CEOI2017] Building Bridges

视频链接:C121 李超树+DP P4655 [CEOI2017] Building Bridges_哔哩哔哩_bilibili Luogu P4655 [CEOI2017] Building Bridges#include <iostream> #include <cstring> #include <algorithm> using namespace std;#define ll long long #define ls u<&l…

实验1-波士顿房价预测

VMware虚拟机 Ubuntu20-LTS python3.6 tensorflow1.15.0 keras2.3.1 运行截图 代码:from sklearn.linear_model import LinearRegression, SGDRegressor, Ridge, LogisticRegression from sklearn.datasets import load_boston from sklearn.model_selection import train_tes…

穿越

题目描述解析 纯搜索,注意不能用 \(dfs\) !!!每次四个方向以及所有传送门,判断 \(rain\) 最早下的时间,判雨;对于兽,如果醒了,等它着再走过去,需要判脚下兽,脚下雨,下一个点的雨。code #include<bits/stdc++.h> #define se second #define fi first using na…

windows下volumetric video conference环境搭建

最近在做volumetric video的rtc,在此记录下相关内容方便之后复习。所采用的end to end平台来自于mmsys24的 Scalable MDC-Based Volumetric Video Delivery for Real-Time One-to-Many WebRTC Conferencing. 源码地址:https://github.com/MatthiasDeFre/webrtc-pc-streaming …

mysql+node.js前后端交互(简单实现注册登录功能)

目录 sql文件 user.js 注册部分 登录部分 对应的表操作 usersql.jsresult.js 用户提交的信息会进行格式化

Linux错误:-bash: Su: command not found

问题:使用 su 命令出错:-bash: Su: command not found解决: 先查看/etc/sudoers.d 文件是否存在find /etc/sudoers.d说明系统已经安装了 sudo,只不过没有配置环境。解决一:使用vi 或 vim 以下命令打开/etc/sudoers文件。vim /etc/sudoers esc --> :wq 保存退出。

【django学习-23】分页功能

前言:当列表界面数据量大的时候,我们一般就要用到分页功能。 下面是已经封装好的组件,使用方法1.分页组件""" 自定义的分页组件,以后如果想要使用这个分页组件,你需要做如下几件事:在视图函数中:def pretty_list(request):# 1.根据自己的情况去筛选自己的…