import tensorflow as tf
from tensorflow.examples.tutorials.mnist import input_data
import os
os.environ[‘TF_CPP_MIN_LOG_LEVEL’] = ‘2’
#载入数据集
mnist = input_data.read_data_sets(“MNIST_data”,one_hot=True)
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)
#计算批次大小
batch_size = 100
n_batch = mnist.train.num_examples // batch_size
#定义两个占位符placeholder
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(‘layer’):
with tf.name_scope(‘wights’):
#链接权重
W = tf.Variable(tf.zeros([784, 10]),name= ‘W’)
variable_summaries(W)
with tf.name_scope(‘baises’):
#偏置值
b = tf.Variable(tf.zeros([10],name= ‘b’))
variable_summaries(b)
#hidden_output
with tf.name_scope(‘wx_plus_b’):
wx_plus_b = tf.matmul(x,W)+b
#output
with tf.name_scope(‘softmax’):
prediction = tf.nn.softmax(wx_plus_b)
#误差函数
with tf.name_scope(‘error’):
#error
error = tf.reduce_mean(tf.square(y-prediction))
tf.summary.scalar(‘error’,error)
with tf.name_scope(‘train’):
#learning
train_step = tf.train.GradientDescentOptimizer(0.2).minimize(error)
#初始化变量
init = tf.global_variables_initializer()
with tf.name_scope(‘accuracy’):
#存放结果(布尔)
correct_accuracy = tf.equal(tf.argmax(y,1),tf.argmax(prediction,1))
with tf.name_scope(‘accuracy’):
#准确率
accuracy = tf.reduce_mean(tf.cast(correct_accuracy,tf.float32))
#合并试图
merged = tf.summary.merge_all()
with tf.Session() as sess:
sess.run(init)
file_writer = tf.summary.FileWriter(‘logs/’,sess.graph)
for epoch in range(50):
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})
file_writer.add_summary(summary,epoch)
acc = sess.run(accuracy,feed_dict= {x:mnist.test.images,y:mnist.test.labels})
print(‘Iter’ + str(epoch) + ‘,accurary’ + str(acc))
命令控制台:tensorboard --logdir=(项目logs所在的路径)
函数不能为张量是因为初始化变量忘记加个括号()
tf.summary.scalar用于显示标量信息
tf.summary.histogram用于显示直方图信息