python实现多层前馈神经网络(手写体识别)

前馈神经网络的图例及推导过程见https://blog.csdn.net/u010089444/article/details/52555567,接下来我们用python语言实现多层前馈神经网络。本例使用的是MINST数据集,由输入层,两个隐藏层,输出层. MNIST数据集中图片的大小为28*28,即每张图片可用一个28*28=784的向量表示.网络输入层的维度是784, 第一层隐藏层包含625个激活单元,第二层隐藏层包含500个激活单元,因此输入层到第一层隐藏层的权重矩阵维度是625*784,第一层到第二层隐藏层的权重矩阵维度是500*625,第二层隐藏层到输出层的权重矩阵维度是10*500,即网络最后输出一个10维向量,表示模型对图片中数字的预测结果.具体代码如下:

import tensorflow as tf
import numpy as np
from tensorflow.examples.tutorials.mnist import input_data
#数据读取
data_sets = input_data.read_data_sets("MNIST_data/", one_hot=True)
trX, trY, teX, teY = data_sets.train.images, data_sets.train.labels, data_sets.test.images, data_sets.test.labels
#占位符
images_placeholder = tf.placeholder("float", [None, 784])
labels_placeholder = tf.placeholder("float", [None, 10])
#每一层都创建于一个唯一的tf.name_scope之下,创建于该作用域之下的所有元素都将带有其前缀
with tf.name_scope('hidden1') as scope1:
    weights1 = tf.Variable(tf.truncated_normal([784, 625], stddev=0.01), name='weights')
#偏置变量维度大小,与weights中的[a,b]中的b相同
    biases = tf.Variable(tf.zeros([625]), name='biases')
#第一层隐藏层
    hidden1 = tf.nn.relu(tf.matmul(images_placeholder, weights1) + biases)
with tf.name_scope('hidden2') as scope2:
    weights2 = tf.Variable(tf.truncated_normal([625, 500], stddev=0.01), name='weights')
    biases = tf.Variable(tf.zeros([500]), name='biases')
#第二层隐藏层
    hidden2 = tf.nn.relu(tf.matmul(hidden1, weights2) + biases)
#输出层,多少隐藏层可以自己定义,自己写,多写几个scope
with tf.name_scope('logits') as scope3:
    weights3 = tf.Variable(tf.truncated_normal([500, 10], stddev=0.01), name='weights')
    biases = tf.Variable(tf.zeros([10]), name='biases')
    logits = tf.matmul(hidden2, weights3) + biases
#损失函数,格式需要写出(logits='',lavels='',....)
cost = tf.reduce_mean(tf.nn.softmax_cross_entropy_with_logits(logits=logits, labels=labels_placeholder))
#采用梯度下降法,步长为0.05
train_op = tf.train.GradientDescentOptimizer(0.05).minimize(cost)
#返回py_x中值最大的index作为预测结果
predict_op = tf.argmax(logits, 1)
with tf.Session() as sess:
    sess.run(tf.initialize_all_variables())
    for i in range(100):#计算100        for start, end in zip(range(0, len(trX), 128), range(128, len(trX) + 1, 128)):
            sess.run(train_op,feed_dict={images_placeholder: trX[start:end], labels_placeholder: trY[start:end]})
        #输出准确率
        print(i, np.mean(np.argmax(teY, axis=1) ==sess.run(predict_op, feed_dict={images_placeholder: teX, labels_placeholder: teY})))

循环训练部分代码借鉴了https://blog.csdn.net/u010089444/article/details/52563514,前馈神经网络隐藏层的数量可以自己定义,自己编写代码,还可以更改激活函数,调整其他参数进行实验,本次循环训练100次,结果如下,准确率达到97.95%:

80 0.9793
81 0.9794
82 0.9794
83 0.9793
84 0.9793
85 0.9793
86 0.9793
87 0.9794
88 0.9793
89 0.9793
90 0.9793
91 0.9792
92 0.9793
93 0.9793
94 0.9794
95 0.9794
96 0.9794
97 0.9794
98 0.9794
99 0.9795

猜你喜欢

转载自blog.csdn.net/zhylhy520/article/details/80746992
今日推荐