全连接网络实现手写数字识别
程序分为三个部分,分别是
mnist_forward.py:前向传播。
mnist_backward.py:反向传播。
mnist_test.py:模型测试。
前向传播
这里搭建了全连接网络。我使用了一个三层的网络。输入的是784个神经元(mnist中一张图片的大小);隐藏层的神经元的个数分别是500,200;输出层是10个神经元,是预测的结果。
下面是mnist_forward.py文件
import tensorflow as tf
import os
os.environ["TF_CPP_MIN_LOG_LEVEL"] = "2" # 忽略tensorflow警告信息
def get_weight(shape,regularizer):
w = tf.Variable(tf.truncated_normal(shape,stddev=0.1))
if regularizer!=None:
tf.add_to_collection('losses',tf.contrib.layers.l2_regularizer(regularizer)(w))
return w
def get_bias(shape):
b = tf.Variable(tf.zeros(shape))
return b
def forward(x,regularizer):
'''
这里定义一个3层的全连接网络
第0层:输入层,784个神经元
第1层:隐藏层,500个神经元
第2层:隐藏层,200个神经元
第3层:输出层,10个神经元
'''
w1 = get_weight([784,500],regularizer)
b1 = get_bias([500])
y1 = tf.nn.leaky_relu(tf.matmul(x,w1) + b1)
w2 = get_weight([500,200],regularizer)
b2 = get_bias([200])
y2 = tf.nn.leaky_relu(tf.matmul(y1,w2) + b2)
w3 = get_weight([200,10],regularizer)
b3 = get_bias([10])
y = tf.matmul(y2,w3) + b3
return y
反向传播
1)参数使用了滑动平均
2)使用指数衰减学习率
3)在训练过程中,进行了模型的保存
下面是mnist_backward.py
import tensorflo