深度学习之tensorflow(四)

#tensorboard

可视化学习。

TensorFlow 可用于训练大规模深度神经网络所需的计算,使用该工具涉及的计算往往复杂而深奥。为了更方便 TensorFlow 程序的理解、调试与优化,发布了一套名为 TensorBoard 的可视化工具。您可以用 TensorBoard 来展现 TensorFlow 图,绘制图像生成的定量指标图以及显示附加数据(如其中传递的图像)。当 TensorBoard 完全配置好后,它将显示如下:

https://www.tensorflow.org/guide/summaries_and_tensorboard?hl=zh_cn】 

 

 

#网络结构可视化

1、在之前【MNIST数据集分类简单版本】的代码基础之上进行修改,

import tensorflow as tf
from tensorflow.examples.tutorials.mnist import input_data

#载入数据集
mnist = input_data.read_data_sets("MNIST_data",one_hot=True)


#每个批次的大小
batch_size = 100
#计算一共有多少个批次
n_batch = mnist.train.num_examples // batch_size

###改变【
#命名空间
with tf.name_scope("input"):
    #定义两个placeholder
    x = tf.placeholder(tf.float32,[None,784],name='x-input')
    y = tf.placeholder(tf.float32,[None,10],name='y-input')
###改变】

#创建一个简单的神经网络
W = tf.Variable(tf.zeros([784,10]))
b = tf.Variable(tf.zeros([10]))
prediction = tf.nn.softmax(tf.matmul(x,W)+b)

#二次代价函数
#loss = tf.reduce_mean(tf.square(y-prediction))
loss = tf.reduce_mean(tf.nn.softmax_cross_entropy_with_logits(labels=y,logits=prediction))

#使用梯度下降法
train_step = tf.train.GradientDescentOptimizer(0.5).minimize(loss)

#初始化变量
init = tf.global_variables_initializer()

#结果存放在一个布尔型列表中
correct_prediction = tf.equal(tf.argmax(y,1),tf.argmax(prediction,1)) #argmax返回一维张量中最大的值所在的位置
#求准确率
accuracy = tf.reduce_mean(tf.cast(correct_prediction,tf.float32))

with tf.Session() as sess:
    sess.run(init)

    ###新增【
    writer = tf.summary.FileWriter('logs/',sess.graph)
    ###新增】

    for epoch in range(1):
        for batch in range(n_batch):
            batch_xs,batch_ys = mnist.train.next_batch(batch_size)
            sess.run(train_step,feed_dict={x:batch_xs,y:batch_ys})
            
        acc = sess.run(accuracy,feed_dict={x:mnist.test.images,y:mnist.test.labels})
        print("Iter " + str(epoch) + ",Testing Accuracy " + str(acc))
  • writer = tf.summary.FileWriter('logs/',sess.graph),意思是存放在当前目录,若没有logs文件夹,则会自动新建一个。

2、打开命令提示符(最好用Anaconda自带的命令行),如果是windows要注意logs文件存在哪个盘就要把命令行移动到哪个盘。

输入:

tensorboard --logdir=【】  //其中【】里复制粘贴logs文件的路径

回车,

结果显示【'tensorboard' 不是内部或外部命令】,然后将tensorboard所在路径添加到系统变量中,再次尝试,结果变成:

C:\Users\HE\logs>tensorboard --logdir=C:\Users\HE\logs
Traceback (most recent call last):
  File "c:\programdata\anaconda3\lib\runpy.py", line 193, in _run_module_as_main

    "__main__", mod_spec)
  File "c:\programdata\anaconda3\lib\runpy.py", line 85, in _run_code
    exec(code, run_globals)
  File "C:\ProgramData\Anaconda3\Scripts\tensorboard.exe\__main__.py", line 9, i
n <module>
  File "c:\programdata\anaconda3\lib\site-packages\tensorboard\main.py", line 50
, in run_main
    program.setup_environment()
  File "c:\programdata\anaconda3\lib\site-packages\tensorboard\lazy.py", line 65
, in __getattr__
    return getattr(load_once(self), attr_name)
  File "c:\programdata\anaconda3\lib\site-packages\tensorboard\lazy.py", line 91
, in wrapper
    cache[arg] = f(arg)
  File "c:\programdata\anaconda3\lib\site-packages\tensorboard\lazy.py", line 51
, in load_once
    module = load_fn()
  File "c:\programdata\anaconda3\lib\site-packages\tensorboard\__init__.py", lin
e 33, in program
    import tensorboard.program as module  # pylint: disable=g-import-not-at-top
  File "c:\programdata\anaconda3\lib\site-packages\tensorboard\program.py", line
 53, in <module>
    from tensorboard.backend import application
  File "c:\programdata\anaconda3\lib\site-packages\tensorboard\backend\applicati
on.py", line 30, in <module>
    import sqlite3
  File "c:\programdata\anaconda3\lib\sqlite3\__init__.py", line 23, in <module>
    from sqlite3.dbapi2 import *
  File "c:\programdata\anaconda3\lib\sqlite3\dbapi2.py", line 27, in <module>
    from _sqlite3 import *
ImportError: DLL load failed: 找不到指定的模块。

试了各种办法依然无果...完全搞不懂为什么,只能暂时放弃【以后解决了再更新这部分:(】


更新:

终于终于弄出来了!

卸了tensorflow重新安装了一次,也出现过这种现象,但是我尝试了一下,先激活tensorflow的环境,再进行tensorboard操作,竟然成功了!

https://blog.csdn.net/wust_lh/article/details/80408505

但是。。。输入这个网址,打不开。。。

网上搜索到:“有些朋友输入“tensorboard --logdir=log文件所在目录”后,并没有任何网址输出,但是这不会影响tensorboard的启动,只需要正常打开谷歌浏览器,输入http://localhost:6006即可正常打开tensorboard。这是由于tensorflow版本不同导致的。”

https://www.cnblogs.com/huaxingtianxia/p/8376625.html

试了一下,果然ok了!终于能打开看到tensorboard界面了!太开心了!

  • 点开 '+' 号可以展开查看内部结构,双击也可以展开或者缩小。
  • namespace:命名空间
  • 椭圆:Op
  • 小圆形:常量

然后:

#创建一个简单的神经网络
W = tf.Variable(tf.zeros([784,10]))
b = tf.Variable(tf.zeros([10]))
prediction = tf.nn.softmax(tf.matmul(x,W)+b)

###改为:
with tf.name_scope('layer'):
    #创建一个简单的神经网络
    with tf.name_scope('Weights'):
        W = tf.Variable(tf.zeros([784,10]))
    with tf.name_scope('biases'):
        b = tf.Variable(tf.zeros([10]))
    with tf.name_scope('wx_plus_b'):
        wx_plus_b = tf.matmul(x,W)+b
    with tf.name_scope('softmax'):
        prediction = tf.nn.softmax(wx_plus_b)

重新运行一次,看有什么变化:

在cmd中按两次 'Ctrl + c ' ,然后暂停之前的,再重新把之前的操作执行一次,然后重新加载那个tensorboard网址。

如果出现之前的图残留现象(很混乱),可以在Jupyter中的kernel选择restart &  clear output再重新操作一次,就可以出现一个清楚的画面:

然后再修改一下:

#二次代价函数
#loss = tf.reduce_mean(tf.square(y-prediction))
loss = tf.reduce_mean(tf.nn.softmax_cross_entropy_with_logits(labels=y,logits=prediction))

#使用梯度下降法
train_step = tf.train.GradientDescentOptimizer(0.5).minimize(loss)

#初始化变量
init = tf.global_variables_initializer()

#结果存放在一个布尔型列表中
correct_prediction = tf.equal(tf.argmax(y,1),tf.argmax(prediction,1)) #argmax返回一维张量中最大的值所在的位置
#求准确率
accuracy = tf.reduce_mean(tf.cast(correct_prediction,tf.float32))

###改成:

#二次代价函数
#loss = tf.reduce_mean(tf.square(y-prediction))
with tf.name_scope('loss'):
    loss = tf.reduce_mean(tf.nn.softmax_cross_entropy_with_logits(labels=y,logits=prediction))

with tf.name_scope('train'):
    #使用梯度下降法
    train_step = tf.train.GradientDescentOptimizer(0.5).minimize(loss)

#初始化变量
#初始化会有默认的名字,不用自己起
init = tf.global_variables_initializer()

with tf.name_scope('accuracy'):
    with tf.name_scope('correct_prediction'):
        #结果存放在一个布尔型列表中
        correct_prediction = tf.equal(tf.argmax(y,1),tf.argmax(prediction,1)) #argmax返回一维张量中最大的值所在的位置
    with tf.name_scope('accuracy'):
        #求准确率
        accuracy = tf.reduce_mean(tf.cast(correct_prediction,tf.float32))

就能得到一个漂亮一些图:

 

#网络运行

一般分析权值和偏置值,以及loss值和准确率。

import tensorflow as tf
from tensorflow.examples.tutorials.mnist import input_data

#载入数据集
mnist = input_data.read_data_sets("MNIST_data",one_hot=True)

#每个批次的大小
batch_size = 100
#计算一共有多少个批次
n_batch = mnist.train.num_examples // batch_size

###增加【

#参数概要
def variable_summaries(var):
    with tf.name_scope('summaries'):
        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.scalar('stddev',stddev) #标准差
        tf.summary.scalar('max',tf.reduce_max(var)) #最大值
        tf.summary.scalar('min',tf.reduce_min(var)) #最小值
        tf.summary.histogram('histogram',var) #直方图

###增加】

#命名空间
with tf.name_scope("input"):
    #定义两个placeholder
    x = tf.placeholder(tf.float32,[None,784],name='x-input')
    y = tf.placeholder(tf.float32,[None,10],name='y-input')

with tf.name_scope('layer'):
    #创建一个简单的神经网络
    with tf.name_scope('Weights'):
        W = tf.Variable(tf.zeros([784,10]))
        
        ###增加【
        variable_summaries(W)
        ###增加】
        
    with tf.name_scope('biases'):
        b = tf.Variable(tf.zeros([10]))
        
        ###增加【
        variable_summaries(b)
        ###增加】
        
    with tf.name_scope('wx_plus_b'):
        wx_plus_b = tf.matmul(x,W)+b
    with tf.name_scope('softmax'):
        prediction = tf.nn.softmax(wx_plus_b)

#二次代价函数
#loss = tf.reduce_mean(tf.square(y-prediction))
with tf.name_scope('loss'):
    loss = tf.reduce_mean(tf.nn.softmax_cross_entropy_with_logits(labels=y,logits=prediction))
    ###增加【
    tf.summary.scalar('loss',loss)
    ###增加】

with tf.name_scope('train'):
    #使用梯度下降法
    train_step = tf.train.GradientDescentOptimizer(0.5).minimize(loss)

#初始化变量
#初始化会有默认的名字,不用自己起
init = tf.global_variables_initializer()

with tf.name_scope('accuracy'):
    with tf.name_scope('correct_prediction'):
        #结果存放在一个布尔型列表中
        correct_prediction = tf.equal(tf.argmax(y,1),tf.argmax(prediction,1)) #argmax返回一维张量中最大的值所在的位置
    with tf.name_scope('accuracy'):
        #求准确率
        accuracy = tf.reduce_mean(tf.cast(correct_prediction,tf.float32))
        ###增加【
        tf.summary.scalar('accuracy',accuracy)
        ###增加】

###增加【
#合并所有的summary
merged = tf.summary.merge_all()
###增加】
        
with tf.Session() as sess:
    sess.run(init)
    writer = tf.summary.FileWriter('logs/',sess.graph)
    for epoch in range(51):
        for batch in range(n_batch):
            batch_xs,batch_ys = mnist.train.next_batch(batch_size)
            ###改变【
            summary,_ = sess.run([merged,train_step],feed_dict={x:batch_xs,y:batch_ys})
            ###改变】
        
        ###增加【
        writer.add_summary(summary,epoch)
        ###增加】
        acc = sess.run(accuracy,feed_dict={x:mnist.test.images,y:mnist.test.labels})
        print("Iter " + str(epoch) + ",Testing Accuracy " + str(acc))

执行之后:

#如果想要看到更多的点,可以:
for i in range(2001):
    #每个批次100个样本
    batch_xs,batch_ys = mnist.train.next_batch(100)
    summary,_ = sess.run([merged,train_step],feed_dict={x:batch_xs,y:batch_ys})
    writer.add_summary(summary,i)
    if i%500==0:
        print(sess.run(accuracy,feed_dict={x:mnist.test.images,y:mnist.test.labels}))

  • 如果loss值是越来越低的,就说明问题不是很大。如果振动比较剧烈,那可能是学习率太大了,一直没有办法收敛,或者是其他原因,需要进一步分析。

*可以根据loss值曲线和准确率曲线来判断模型是否在正常工作。

 

  • 分布图,颜色越深分布越多。

 

#可视化

import tensorflow as tf
from tensorflow.examples.tutorials.mnist import input_data
###增加【
from tensorflow.contrib.tensorboard.plugins import projector
###增加】

#载入数据集
mnist = input_data.read_data_sets("MNIST_data",one_hot=True)

###增加【

#运行次数
max_steps = 1001
#图片数量
image_num = 3000
#文件路径
DIR = 'C:/Users/HE/'

#定义会话
sess = tf.Session()

#载入图片
embedding = tf.Variable(tf.stack(mnist.test.images[:image_num]),trainable=False,name='embedding')

###增加】

#参数概要
def variable_summaries(var):
    with tf.name_scope('summaries'):
        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.scalar('stddev',stddev) #标准差
        tf.summary.scalar('max',tf.reduce_max(var)) #最大值
        tf.summary.scalar('min',tf.reduce_min(var)) #最小值
        tf.summary.histogram('histogram',var) #直方图

#命名空间
with tf.name_scope("input"):
    #定义两个placeholder
    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)

###增加】

with tf.name_scope('layer'):
    #创建一个简单的神经网络
    with tf.name_scope('Weights'):
        W = tf.Variable(tf.zeros([784,10]),name='W')
        variable_summaries(W)
    with tf.name_scope('biases'):
        b = tf.Variable(tf.zeros([10]),name='b')
        variable_summaries(b)
    with tf.name_scope('wx_plus_b'):
        wx_plus_b = tf.matmul(x,W) + b
    with tf.name_scope('softmax'):
        prediction = tf.nn.softmax(wx_plus_b)

with tf.name_scope('loss'):
    #交叉代价函数
    loss = tf.reduce_mean(tf.nn.softmax_cross_entropy_with_logits(labels=y,logits=prediction))
    tf.summary.scalar('loss',loss)

with tf.name_scope('train'):
    #使用梯度下降法
    train_step = tf.train.GradientDescentOptimizer(0.5).minimize(loss)

#初始化变量
init = tf.global_variables_initializer()
###增加【
sess.run(init)
###增加】

with tf.name_scope('accuracy'):
    with tf.name_scope('correct_prediction'):
        #结果存放在一个布尔型列表中
        correct_prediction = tf.equal(tf.argmax(y,1),tf.argmax(prediction,1)) #argmax返回一维张量中最大的值所在的位置
    with tf.name_scope('accuracy'):
        #求准确率
        accuracy = tf.reduce_mean(tf.cast(correct_prediction,tf.float32))
        tf.summary.scalar('accuracy',accuracy)

###增加【

#生成metadata文件
if tf.gfile.Exists(DIR + 'projector/projector/metadata.tsv'):
    tf.gfile.DeleteRecursively(DIR + 'projector/projector/metadata.tsv')
with open(DIR + 'projector/projector/metadata.tsv', 'w') as f:
    labels = sess.run(tf.argmax(mnist.test.labels[:],1))
    for i in range(image_num):
        f.write(str(labels[i]) + '\n')

###增加】
        
#合并所有的summary
merged = tf.summary.merge_all()

###增加【

#根据tensorflow官网上的startup例子
projector_writer = tf.summary.FileWriter(DIR + 'projector/projector',sess.graph)
saver = tf.train.Saver()
config = projector.ProjectorConfig()
embed = config.embeddings.add()
embed.tensor_name = embedding.name
embed.metadata_path = DIR + 'projector/projector/metadata.tsv'
embed.sprite.image_path = DIR + 'projector/data/mnist_10k_sprite.png'
embed.sprite.single_image_dim.extend([28,28])
projector.visualize_embeddings(projector_writer,config)

###增加】

###改变【
for i in range(max_steps):
    #每个批次100个样本
    batch_xs,batch_ys = mnist.train.next_batch(100)
    run_options = tf.RunOptions(trace_level=tf.RunOptions.FULL_TRACE)
    run_metadata = tf.RunMetadata()
    summary,_ = sess.run([merged,train_step],feed_dict={x:batch_xs,y:batch_ys},options=run_options,run_metadata=run_metadata)
    projector_writer.add_run_metadata(run_metadata, 'step%03d' % i)
    projector_writer.add_summary(summary,i)
    
    if i%100 == 0:
        acc = sess.run(accuracy,feed_dict={x:mnist.test.images,y:mnist.test.labels})
        print("Iter " + str(i) + ",Testing Accuracy " + str(acc))

###改变】

###增加【

saver.save(sess, DIR + 'projector/projector/a_model.ckpt', global_step=max_steps)
projector_writer.close()
sess.close()

###增加】
  • 运行之前应该在文件路径(代码中的文件路径请设为自己的文件路径)下新建文件:projector,而该文件中还要新建两个文件:projector和data
  • 其中data要存放一个png文件:链接:https://pan.baidu.com/s/1EXZoUzJz6ehEErWEXMP1hQ  提取码:smuj   图片为mnist_10k_sprite.png

 

执行之后,打开tensorboard:

  • 训练集里的图片

  • 一开始是混乱的。
  • 然后点T-SNE开始训练。

迭代363次后变为:

 

#作业

1、实现程序;

2、可视化。

 


PS.此为学习《深度学习框架Tensorflow学习与应用》课程的笔记。【http://www.bilibili.com/video/av20542427/?share_source=copy_link&p=4&ts=1551709559&share_medium=iphone&bbid=7db773463cc4248e755f030556bc67d1】

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值