Tensorflow学习5-1:Tensorboard网络结构

例子

1
2
import tensorflow as tf
from tensorflow.examples.tutorials.mnist import input_data
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
#载入数据集
mnist = input_data.read_data_sets("MNIST_data", one_hot=True)

#每个批次大小
batch_size = 100
#计算有多少批次
batch_num = mnist.train.num_examples // batch_size
# STEP 1
with tf.name_scope("input"):
input_x = tf.placeholder(tf.float32, [None, 784], name="input_x")
input_y = tf.placeholder(tf.float32, [None, 10], name="input_y")

#创建神经网络模型
with tf.name_scope("layers"):
W1 = tf.Variable(tf.truncated_normal([784,128], 0.,0.5), name="W1")
b1 = tf.Variable(tf.zeros([128]) + 0.1, name="b1")
L1 = tf.nn.relu(tf.matmul(input_x, W1) + b1, name="L1")

W2 = tf.Variable(tf.truncated_normal([128,10], 0.,0.5), name="W2")
b2 = tf.Variable(tf.zeros([10]) + 0.1, name="b2")
L2 = tf.add(tf.matmul(L1, W2), b2, name="L2")
with tf.name_scope("loss"):
loss = tf.reduce_mean(tf.nn.softmax_cross_entropy_with_logits(logits=L2, labels=input_y))
with tf.name_scope("train_and_optimizer"):
train = tf.train.GradientDescentOptimizer(0.2).minimize(loss)

#获取用于显示的精度——优化效果
with tf.name_scope("accuracy"):
correct_indices = tf.equal(tf.argmax(input_y, 1), tf.argmax(L2, 1))
accuracy = tf.reduce_mean(tf.cast(correct_indices, tf.float32))

init = tf.global_variables_initializer()
with tf.Session() as sess:
sess.run(init)
# STEP 2
writer = tf.summary.FileWriter("D:/Tensorboard/logs", sess.graph)
for epoch in range(5):
for batch in range(batch_num):
batch_xs, batch_ys = mnist.train.next_batch(batch_size)
sess.run(train, feed_dict={input_x:batch_xs, input_y:batch_ys})
_accuracy = sess.run(accuracy, feed_dict={input_x:mnist.test.images, input_y:mnist.test.labels})
print("epoch:"+ str(epoch) + ", accuracy:"+ str(_accuracy))

Extracting MNIST_data\train-images-idx3-ubyte.gz
Extracting MNIST_data\train-labels-idx1-ubyte.gz
Extracting MNIST_data\t10k-images-idx3-ubyte.gz
Extracting MNIST_data\t10k-labels-idx1-ubyte.gz
epoch:0, accuracy:0.909
epoch:1, accuracy:0.9272
epoch:2, accuracy:0.9358
epoch:3, accuracy:0.942
epoch:4, accuracy:0.9459

总结

Tensorboard使用方法:

STEP 1:在sess外部给tensor加上命名空间name_scope 和 name。
name_scope对应矩形
name对应矩形内部的tensor

1
2
3
with tf.name_scope("input"):
input_x = tf.placeholder(tf.float32, [None, 784], name="input_x")
input_y = tf.placeholder(tf.float32, [None, 10], name="input_y")

STEP 2:在sess内部加上打印日志

1
writer = tf.summary.FileWriter("logs", sess.graph)

STEP 3:运行代码。
如果之前运行过,可以restart kernel选择“Restart & Run All”

STEP 4:将tensorboard目录D:\Anaconda3\envs\tensorflow\Scripts添加的环境变量中,打开anaconda cmd,切换到log的相应盘符下,否则tensorboard无法显示。接下来输入命令

1
tensorboard --logdir=D:/Tensorflow/logs

复制生成的地址在浏览器打开

꧁༺The༒End༻꧂