tensorborad(一):绘制graph,网络结构图

本博客展示的仅仅只是tensorboard画出网络结构图,使得画图更加清晰,其他操作将在下一篇中展示,作为画图功能,只要用到以下两个操作

1. 命名空间

2. 将图结构利用语句tf.summary.FileWriter(‘logs/’, sess.graph)写入

#_*_coding:utf-8_*_
import tensorflow as tf
from tensorflow.examples.tutorials.mnist import input_data

#利用tensorflow自带的数据集下载mnist数据集并直接处理返回
#若是想用自己的代码(numpy)来解析mnist数据集可以参考博客:
#https://blog.csdn.net/qiu931110/article/details/80113147
mnist = input_data.read_data_sets('MNIST_data',one_hot = True)

#定义超参数
iteration_num = 1
learning_rate = 0.2
batch_size = 64
n_batch = mnist.train.num_examples // batch_size

#利用tensorboard的基础工作,就是要定义好命名空间
#定义好网络训练过程中的输入数据和标签(也属于输入数据之一)
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('weight'):
    with tf.name_scope('w_weight'):
        w = tf.Variable(tf.zeros([784,10]))
    with tf.name_scope('b_weight'):
        b = tf.Variable(tf.zeros([10]))
    with tf.name_scope('wx'):
        wx = tf.matmul(x,w)
    with tf.name_scope('softmax'):
        prd = tf.nn.softmax(wx + b)

#定义网络损失函数
with tf.name_scope('loss'):
    loss = tf.reduce_mean(tf.nn.softmax_cross_entropy_with_logits(labels=y, logits=prd))

#定义使用的训练器
with tf.name_scope('train'):
    train = tf.train.GradientDescentOptimizer(learning_rate).minimize(loss)

#定义网络精度求解
with tf.name_scope('accuracy_part'):
    with tf.name_scope('correct_prd'):
        correct_prd = tf.equal(tf.argmax(y,1), tf.argmax(prd,1))
    with tf.name_scope('accuracy'):
        accuracy = tf.reduce_mean(tf.cast(correct_prd,tf.float32))

#初始化变量,这个不需要定义命名空间,因为它默认的命名空间就是init
init = tf.global_variables_initializer()

#到此为止,以上已经把网络结构都描述清楚,命名空间也搞定了
#只需要在训练过程中将上述的网络结构写入到一个文件中就OK了
#这个写入的指令为:tf.summary.FileWriter('logs/', sess.graph)



with tf.Session() as sess:
    sess.run(init)
    #将网络图结构写入的语句就写在最开始
    #这就相当于已经写完了
    writer = tf.summary.FileWriter('logs/', sess.graph)
    for epoch in range(iteration_num):
        for batch in range(n_batch):
            #这里的语句利用了tensorflow的库,也可以自己定义next_batch函数操作
            batch_xs,batch_ys = mnist.train.next_batch(batch_size)
            sess.run(train, feed_dict={x:batch_xs, y:batch_ys})

        #没结束一次epoch的迭代,计算一次测试集上的准确率
        acc = sess.run(accuracy,feed_dict = {x:mnist.test.images, y :mnist.test.labels})
        print('Iteration_num' + str(epoch)+',Testing_acc is '+str(acc))




结果分析

这里写图片描述

猜你喜欢

转载自blog.csdn.net/qiu931110/article/details/80137287