本文主要是介绍清华AI自强计划作业3-Part3 tensorflow-MNIST-NN,希望对大家解决编程问题提供一定的参考价值,需要的开发者们随着小编来一起学习吧!
如何将作业提供的神经网络模型优化跑出99%的准确率
导读
mnist数据集基本上可以算做是数据科学里的hello world程序。
对于Part3部分的作业,按照注释部分的提示可以达到96%的准确率。
关于准确率的进一步优化
激活函数
在尝试了不同的激活函数sigmoid、relu、tanh之后,在本次作业的模型里sigmoid的表现较后两者更为出色。
神经元
通过增加A1、A2层的神经元个数同样可以提高训练精度,但神经元的个数并不是越多越好,需要进行不断调试。
学习率
对于学习率的设置,通过调试也可以提高训练精度。注释部分的提示原学习率设为0.01,但经过手动调试之后当Lr=0.05时,可以获得最高的精度。此外,还可以借助TensorFlow提供的一种更灵活的学习率设置方法——指数衰减法。tf.train.exponential_decay函数实现了指数衰减学习率。下面给出一段代码来示范如何在TensorFlow中使用tf.train.exponential_decay函数。
global_step = tf.Variable(0)#通过exponential_decay函数生成学习率。learning_rate = tf.train.exponential_decay(0.1,global_step,100,0.96,staircase=True)# 在训练利用梯度下降法中,使用指数衰减学习率。在minimize函数中传入global_step将自动更新#global_step参数,从而使得学习率也得到相应更新train_step = tf.train.GradientDescentOptimizer(learning_rate)\.minimize(cross_entropy,global_step=global_step)
代码实现
from tensorflow.examples.tutorials.mnist import input_data
import tensorflow as tf# MNIST数据存放的路径
file = "../MNIST"# 导入数据,首先检测file路径下是否存在数据集,若不存在,则到网上下载.
# MNIST下载地址:http://yann.lecun.com/exdb/mnist/
# 注意:下载后需要解压
mnist = input_data.read_data_sets(file, one_hot=True)#读取数据集,标签数据设置为one-hot格式。即n维标签中只有一个数据为1,其余为0# 模型的输入和输出
# 为模型的输入输出申请占位符,作为外部数据与网络模型的交互接口
# 784=28*28
x = tf.placeholder(tf.float32, shape=[None,784]) #申请占位符 输入图像 N*784的矩阵 [None, 784]
y_ = tf.placeholder(tf.float32, shape=[None,10]) #申请占位符 输入label N*10的矩阵[None, 10]# 将tensor图中的输入和变量进行计算 通过tf.layers.dense搭建全连接网络层,并为该层设置对应的输入、神经元个数、激活函数
# 通过units设置神经元的个数,通过activation设置激活函数,可设定的激活函数,请参考https://tensorflow.google.cn/api_docs/python/tf/nn/softmaxA1 = tf.layers.dense(inputs=x, units=96,activation=tf.nn.sigmoid) #添加全连接层,神经元个数为96个,激活函数为sigmoid、tanh或relu
A2 = tf.layers.dense(inputs=A1,units=96,activation=tf.nn.sigmoid) #添加全连接层,神经元个数为96个,激活函数为sigmoid、tanh或relu
y = tf.layers.dense(inputs=A2,units=10, activation=tf.nn.softmax) #添加全连接层,设置激活函数为sigmoid或softmax,由于输出类别是10,所以输出层神经元个数为10# 交叉熵 用来度量y_与y之间的差异性
# y_表示样本的标签 one-hot形式 ; y表示tensor流图计算出的值,即预测值
cross_entropy = -tf.reduce_sum(y_*tf.log(y))#对损失求和#global_step = tf.Variable(0)
##learning_rate = tf.train.exponential_decay(0.1,global_step,100,0.96,staircase=True)
# 训练 利用梯度下降法,以0.01的学习率最小化目标函数(cross_entropy)
train_step = tf.train.GradientDescentOptimizer(0.05).minimize(cross_entropy) #设置随机梯度下降的学习率为0.01,最小化目标函数为cross_entropy################################### 测试 ###################################
# 计算模型预测结果与标签中相等的部分
# 调用tf.equal计算模型预测结果y与标签结果y_的差异,预测正确则返回1,预测错误则返回0;
# tf.argmax(y, 1)为计算y中每行数据最大值的索引;
correct_prediction = tf.equal(tf.argmax(y, 1), tf.argmax(y_, 1))# 根据correct_prediction计算模型预测精度
accuracy = tf.reduce_mean(tf.cast(correct_prediction, tf.float32))# 创建Session,用于启动tensor图
sess = tf.InteractiveSession()# 调用global_variables_initializer函数,将前面定义的Variable变量按照设置的初始化方式,进行初始化
sess.run(tf.global_variables_initializer()) #执行tf.global_variables_initializer(),初始化模型参数#循环训练,设置迭代次数为20000
for i in range(20000):#选取mnist训练数据集,设置minibatchsize为50,即选取样本集中的50个样本batch = mnist.train.next_batch(50)if i% 1000 == 0:train_accuracy = accuracy.eval(feed_dict={x:batch[0],y_:batch[1]})print("step %d, training accuracy %g" % (i, train_accuracy))#启动tensor流图,并执行训练,输入数据为图像(batch[0])和对应的标签(batch[1])train_step.run(feed_dict={x: batch[0], y_: batch[1]})# 启动tensor流图,计算模型预测精度,模型输入数据为train/test的图像和对应标签
print(sess.run(accuracy, feed_dict={x: mnist.train.images, y_:mnist.train.labels}))#计算模型在训练集上的准确率
print(sess.run(accuracy, feed_dict={x: mnist.test.images, y_:mnist.test.labels}))#计算模型在测试集上的准确率# 结果输出
logFileName = "logText.txt"
logFile = open(logFileName, "w")
logFile.write(str(sess.run(accuracy, feed_dict={x: mnist.train.images, y_:mnist.train.labels})))
logFile.write("\n")
logFile.write(str(sess.run(accuracy, feed_dict={x: mnist.test.images, y_:mnist.test.labels})))
logFile.close()
运行结果
参考资料
https://tensorflow.google.cn/api_docs/python/
TensorFlow实战Google深度学习框架(第2版)
这篇关于清华AI自强计划作业3-Part3 tensorflow-MNIST-NN的文章就介绍到这儿,希望我们推荐的文章对编程师们有所帮助!