import tensorflow as tf
from tensorflow.examples.tutorials.mnist import input_data
#加载手写数字图像数据
minist=input_data.read_data_sets('MNIST_data', one_hot=True)
#定义每个批次的大小
batch_size=200
#计算共有多少批次
enom=minist.train.num_examples//batch_size
#定义神经网络的输入数据placeholder
x_input=tf.placeholder(tf.float32, [None,784])
y_input=tf.placeholder(tf.float32, [None,10])
#定义神经网络
W_L1=tf.Variable(tf.zeros([784,10], tf.float32))
b_L1=tf.Variable(tf.zeros([10],tf.float32))
Wx_plus_b_L1=tf.matmul(x_input,W_L1)+b_L1
prediction=tf.nn.softmax(Wx_plus_b_L1)
#定义损失函数
loss=tf.reduce_mean(tf.square(prediction-y_input))
#定义优化器
optimizer=tf.train.GradientDescentOptimizer(0.2).minimize(loss)
#计算准确率
correct_prediction=tf.equal(tf.argmax(y_input,1), tf.argmax(prediction,1))
accuracy=tf.reduce_mean(tf.cast(correct_prediction, tf.float32))
#初始化变量
init=tf.global_variables_initializer()
with tf.Session() as sess:
sess.run(init)
for epoch in range(200):
for step in range(enom):
x_data,y_data=minist.train.next_batch(batch_size)
sess.run(optimizer,feed_dict={x_input:x_data,y_input:y_data})
print('批次:%f 准确率:%f'%(epoch+1,sess.run(accuracy,feed_dict={x_input:minist.test.images,y_input:minist.test.labels})))
#输出:
91%的准确率
改进后的代码:
import tensorflow as tf
from tensorflow.examples.tutorials.mnist import input_data
#加载手写数字图像数据
minist=input_data.read_data_sets('MNIST_data', one_hot=True)
#定义每个批次的大小
batch_size=200
#计算共有多少批次
enom=minist.train.num_examples//batch_size
#定义神经网络的输入数据placeholder
x_input=tf.placeholder(tf.float32, [None,784])
y_input=tf.placeholder(tf.float32, [None,10])
#定义神经网络-中间层
W_L1=tf.Variable(tf.zeros([784,100], tf.float32))
b_L1=tf.Variable(tf.zeros([100],tf.float32))
Wx_plus_b_L1=tf.matmul(x_input,W_L1)+b_L1
# prediction=tf.nn.softmax(Wx_plus_b_L1)
L1=tf.nn.sigmoid(Wx_plus_b_L1)
droupout_L1=tf.nn.dropout(L1, 0.5)
#定义神经网络-输出层
W_L2=tf.Variable(tf.zeros([100,10], tf.float32))
b_L2=tf.Variable(tf.zeros([10],tf.float32))
Wx_plus_b_L2=tf.matmul(droupout_L1,W_L2)+b_L2
L2=tf.nn.sigmoid(Wx_plus_b_L2)
prediction=tf.nn.softmax(L2)
#定义损失函数
loss=tf.reduce_mean(tf.square(prediction-y_input))
#定义优化器
optimizer=tf.train.AdamOptimizer(1e-3)
grads_vars=optimizer.compute_gradients(loss)
train_op=optimizer.apply_gradients(grads_vars)
#计算准确率
correct_prediction=tf.equal(tf.argmax(y_input,1), tf.argmax(prediction,1))
accuracy=tf.reduce_mean(tf.cast(correct_prediction, tf.float32))
#初始化变量
init=tf.global_variables_initializer()
with tf.Session() as sess:
sess.run(init)
for epoch in range(1000):
for step in range(enom):
x_data,y_data=minist.train.next_batch(batch_size)
sess.run(train_op,feed_dict={x_input:x_data,y_input:y_data})
print('批次:%i 准确率:%f loss:%f'%(epoch+1,sess.run(accuracy,feed_dict={x_input:minist.test.images,y_input:minist.test.labels}),sess.run(loss,feed_dict={x_input:minist.test.images,y_input:minist.test.labels})))
经验:
- 重新加入一层神经元后(还是梯度下降算法),准确率的提升非常慢,反倒不如单层神经网络,几乎不提升,且在20批次后出现过拟合现象,准确率下降非常明显
- 改用Adam优化器,训练效果小幅上升,但也同样出现过拟合现象
- 加入droupout层后,测试集的准确率提升非常明显,第一波训练完后,准确率达到89%