程序
下面的例子是两层全连接网络,实现手写数字识别的案例。
from tensorflow.examples.tutorials.mnist import input_data
import tensorflow as tf
import os
os.environ["TF_CPP_MIN_LOG_LEVEL"] = "2" # 忽略tensorflow警告信息
mnist = input_data.read_data_sets('MNIST_data',one_hot=True)
batch_size = 100
n_batch = mnist.train.num_examples // batch_size
lr = 0.01
#初始化
#命名空间
with tf.name_scope("input"):
x = tf.placeholder(tf.float32,[None,784],name='x')
y_ = tf.placeholder(tf.float32,[None,10],name='y_')
#创建网络
with tf.name_scope('Layer1'):
with tf.name_scope('weight1'):
w1 = tf.Variable(tf.truncated_normal([784,500]),name='w1')
with tf.name_scope("biases"):
b1 = tf.Variable(tf.zeros([500]),name='b1')
with tf.name_scope("y1"):
y1 = tf.nn.tanh(tf.matmul(x,w1)+b1,name='y1')
with tf.name_scope("Layer2"):
with tf.name_scope('weight2'):
w2 = tf.Variable(tf.truncated_normal([500,10]),name='w2')
with tf.name_scope("biases2"):
b2 = tf.Variable(tf.zeros([10]),name='b2')
with tf.name_scope("y"):
y = tf.nn.softmax(tf.matmul(y1,w2)+b2,name='y') #输出信号总和
with tf.name_scope("loss"):
loss = tf.reduce_mean(tf.nn.softmax_cross_entropy_with_logits(labels=y_,logits=y))
tf.summary.scalar('loss',loss)
#训练
with tf.name_scope("train"):
train_stap = tf.train.GradientDescentOptimizer(lr).minimize(loss)
#准确率
with tf.name_scope("accuracy"):
correct_prediction = tf.equal(tf.argmax(y_,1),tf.argmax(y,1))
accuracy = tf.reduce_mean(tf.cast(correct_prediction,tf.float32))
tf.summary.scalar('accuracy',accuracy)
merged = tf.summary.merge_all()
with tf.Session() as sess:
init_op = tf.global_variables_initializer()
sess.run(init_op)
write = tf.summary.FileWriter('E://TensorBoard//test',sess.graph)
for epoch in range(500):
for batch in range(n_batch):
batch_xs,batch_ys = mnist.train.next_batch(batch_size)
_,summery,loss_val=sess.run([train_stap,merged,loss],feed_dict={x:batch_xs, y_:batch_ys})
write.add_summary(summery,epoch)
acc = sess.run(accuracy,feed_dict={x:mnist.test.images,y_:mnist.test.labels})
print("Atfer %d steps, Accuracy is %g, loss is %g" %(epoch,acc,loss_val))
网络结构
accyracy