在我的上一篇随笔中,采用了单层神经网络来对MNIST进行训练,在测试集中只有约90%的正确率。这次换一种神经网络(多层神经网络)来进行训练和测试。

1、获取MNIST数据

  MNIST数据集只要一行代码就可以获取的到,非常方便。关于MNIST的基本信息可以参考我的上一篇随笔。

mnist = input_data.read_data_sets('./data/mnist', one_hot=True)

2、模型基本结构

  本次采用的训练模型为三层神经网络结构,输入层节点数与MNIST一行数据的长度一致,为784;输出层节点数与数字的类别数一致,为10;隐藏层节点数为50个;每次训练的mini-batch数量为64,;最大训练周期为50000。

 inputSize  = 784
outputSize = 10
hiddenSize = 50
batchSize = 64
trainCycle = 50000

3、输入层

  输入层用于接收每次小批量样本的输入,先通过placeholder来进行占位,在训练时才传入具体的数据。值得注意的是,在生成输入层的tensor时,传入的shape中有一个‘None’,表示每次输入的样本的数量,该‘None’表示先不作具体的指定,在真正输入的时候再根据实际的数据来进行推断。这个很方便,但也是有条件的,也就是通过该方法返回的tensor不能使用简单的加(+)减(-)乘(*)除(/)符号来进行计算(否则将会报错),需要用TensorFlow中的相关函数来进行代替。

inputLayer = tf.placeholder(tf.float32, shape=[None, inputSize])

4、隐藏层

  在神经网络中,隐藏层的作用主要是提取数据的特征(feature)。这里的权重参数采用了 tensorflow.truncated_normal() 函数来进行生成,与上次采用的 tensorflow.

random_normal() 不一样。这两者的作用都是生成指定形状、期望和标准差的符合正太分布随机变量。区别是 truncated_normal 函数对随机变量的范围有个限制(与期望的偏差在2个标准差之内,否则丢弃)。另外偏差项这里也使用了变量的形式,也可以采用常量来进行替代。

  激活函数为sigmoid函数。

 hiddenWeight = tf.Variable(tf.truncated_normal([inputSize, hiddenSize], mean=0, stddev=0.1))
hiddenBias = tf.Variable(tf.truncated_normal([hiddenSize]))
hiddenLayer = tf.add(tf.matmul(inputLayer, hiddenWeight), hiddenBias)
hiddenLayer = tf.nn.sigmoid(hiddenLayer)

5、输出层

  输出层与隐藏层类似,只是节点数不一样。

 outputWeight = tf.Variable(tf.truncated_normal([hiddenSize, outputSize], mean=0, stddev=0.1))
outputBias = tf.Variable(tf.truncated_normal([outputSize], mean=0, stddev=0.1))
outputLayer = tf.add(tf.matmul(hiddenLayer, outputWeight), outputBias)
outputLayer = tf.nn.sigmoid(outputLayer)

6、输出标签

  跟输入层一样,也是先占位,在最后训练的时候再传入具体的数据。标签,也就是每一个样本的正确分类。

outputLabel = tf.placeholder(tf.float32, shape=[None, outputSize])

7、损失函数

  这里采用的是交叉熵损失函数。注意用的是v2版本,第一个版本已被TensorFlow声明为deprecated,准备废弃了。

loss = tf.reduce_mean(tf.nn.softmax_cross_entropy_with_logits_v2(labels=outputLabel, logits=outputLayer))

8、优化器与目标函数

  优化器采用了Adam梯度下降法,我试过了普通的GradientDescentOptimizer,效果不如Adam;也用过Adadelta,结果几乎收敛不了。

  目标函数就是最小化损失函数。

optimizer = tf.train.AdamOptimizer()
target = optimizer.minimize(loss)

9、训练过程

  先创建一个会话,然后初始化tensors,最后进行迭代训练。模型的收敛速度很快,在1000次的时候就达到了大概90%的正确率。

 with tf.Session() as sess:
sess.run(tf.global_variables_initializer()) for i in range(trainCycle):
batch = mnist.train.next_batch(batchSize)
sess.run(target, feed_dict={inputLayer: batch[0], outputLabel: batch[1]}) if i % 1000 == 0:
corrected = tf.equal(tf.argmax(outputLabel, 1), tf.argmax(outputLayer, 1))
accuracy = tf.reduce_mean(tf.cast(corrected, tf.float32))
accuracyValue = sess.run(accuracy, feed_dict={inputLayer: batch[0], outputLabel: batch[1]})
print(i, 'train set accuracy:', accuracyValue)

模型训练输出:

10、测试训练结果

  在测数据集上测试。准确率达到96%,比单层的神经网络好很多。

     corrected = tf.equal(tf.argmax(outputLabel, 1), tf.argmax(outputLayer, 1))
accuracy = tf.reduce_mean(tf.cast(corrected, tf.float32))
accuracyValue = sess.run(accuracy, feed_dict={inputLayer: mnist.test.images, outputLabel: mnist.test.labels})
print("accuracy on test set:", accuracyValue)

测试集上的输出:

附:

  完整代码如下:

 import tensorflow as tf
from tensorflow.examples.tutorials.mnist import input_data mnist = input_data.read_data_sets('./data/mnist', one_hot=True) inputSize = 784
outputSize = 10
hiddenSize = 50
batchSize = 64
trainCycle = 50000 # 输入层
inputLayer = tf.placeholder(tf.float32, shape=[None, inputSize]) # 隐藏层
hiddenWeight = tf.Variable(tf.truncated_normal([inputSize, hiddenSize], mean=0, stddev=0.1))
hiddenBias = tf.Variable(tf.truncated_normal([hiddenSize]))
hiddenLayer = tf.add(tf.matmul(inputLayer, hiddenWeight), hiddenBias)
hiddenLayer = tf.nn.sigmoid(hiddenLayer) # 输出层
outputWeight = tf.Variable(tf.truncated_normal([hiddenSize, outputSize], mean=0, stddev=0.1))
outputBias = tf.Variable(tf.truncated_normal([outputSize], mean=0, stddev=0.1))
outputLayer = tf.add(tf.matmul(hiddenLayer, outputWeight), outputBias)
outputLayer = tf.nn.sigmoid(outputLayer) # 标签
outputLabel = tf.placeholder(tf.float32, shape=[None, outputSize]) # 损失函数
loss = tf.reduce_mean(tf.nn.softmax_cross_entropy_with_logits_v2(labels=outputLabel, logits=outputLayer)) # 优化器
optimizer = tf.train.AdamOptimizer() # 训练目标
target = optimizer.minimize(loss) # 训练
with tf.Session() as sess:
sess.run(tf.global_variables_initializer()) for i in range(trainCycle):
batch = mnist.train.next_batch(batchSize)
sess.run(target, feed_dict={inputLayer: batch[0], outputLabel: batch[1]}) if i % 1000 == 0:
corrected = tf.equal(tf.argmax(outputLabel, 1), tf.argmax(outputLayer, 1))
accuracy = tf.reduce_mean(tf.cast(corrected, tf.float32))
accuracyValue = sess.run(accuracy, feed_dict={inputLayer: batch[0], outputLabel: batch[1]})
print(i, 'train set accuracy:', accuracyValue) # 测试
corrected = tf.equal(tf.argmax(outputLabel, 1), tf.argmax(outputLayer, 1))
accuracy = tf.reduce_mean(tf.cast(corrected, tf.float32))
accuracyValue = sess.run(accuracy, feed_dict={inputLayer: mnist.test.images, outputLabel: mnist.test.labels})
print("accuracy on test set:", accuracyValue) sess.close()

本文地址:https://www.cnblogs.com/laishenghao/p/9736696.html

TensorFlow 训练MNIST数据集(2)—— 多层神经网络的更多相关文章

  1. TensorFlow训练MNIST数据集(3) —— 卷积神经网络

    前面两篇随笔实现的单层神经网络 和多层神经网络, 在MNIST测试集上的正确率分别约为90%和96%.在换用多层神经网络后,正确率已有很大的提升.这次将采用卷积神经网络继续进行测试. 1.模型基本结构 ...

  2. TensorFlow训练MNIST数据集(1) —— softmax 单层神经网络

    1.MNIST数据集简介 首先通过下面两行代码获取到TensorFlow内置的MNIST数据集: from tensorflow.examples.tutorials.mnist import inp ...

  3. 2、TensorFlow训练MNIST

    装载自:http://www.tensorfly.cn/tfdoc/tutorials/mnist_beginners.html TensorFlow训练MNIST 这个教程的目标读者是对机器学习和T ...

  4. 使用caffe训练mnist数据集 - caffe教程实战(一)

    个人认为学习一个陌生的框架,最好从例子开始,所以我们也从一个例子开始. 学习本教程之前,你需要首先对卷积神经网络算法原理有些了解,而且安装好了caffe 卷积神经网络原理参考:http://cs231 ...

  5. 实践详细篇-Windows下使用VS2015编译的Caffe训练mnist数据集

    上一篇记录的是学习caffe前的环境准备以及如何创建好自己需要的caffe版本.这一篇记录的是如何使用编译好的caffe做训练mnist数据集,步骤编号延用上一篇 <实践详细篇-Windows下 ...

  6. 一个简单的TensorFlow可视化MNIST数据集识别程序

    下面是TensorFlow可视化MNIST数据集识别程序,可视化内容是,TensorFlow计算图,表(loss, 直方图, 标准差(stddev)) # -*- coding: utf-8 -*- ...

  7. MNIST数据集上卷积神经网络的简单实现(使用PyTorch)

    设计的CNN模型包括一个输入层,输入的是MNIST数据集中28*28*1的灰度图 两个卷积层, 第一层卷积层使用6个3*3的kernel进行filter,步长为1,填充1.这样得到的尺寸是(28+1* ...

  8. TensorFlow训练MNIST报错ResourceExhaustedError

    title: TensorFlow训练MNIST报错ResourceExhaustedError date: 2018-04-01 12:35:44 categories: deep learning ...

  9. 基于 tensorflow 的 mnist 数据集预测

    1. tensorflow 基本使用方法 2. mnist 数据集简介与预处理 3. 聚类算法模型 4. 使用卷积神经网络进行特征生成 5. 训练网络模型生成结果 how to install ten ...

随机推荐

  1. 如何扩展 Azure 资源组中虚拟机的 OS 驱动器

    概述 在资源组中通过从 Azure 应用商店部署映像来创建新的虚拟机 (VM) 时,默认的 OS 驱动器空间为 127 GB. 尽管可以将数据磁盘添加到 VM(数量取决于所选择的 SKU),并且我们建 ...

  2. elasticsearch DSL查询

    总结一个DSL的用法吧,语法网上查去,只记录一点心得,也是研究了半天,太麻烦了 先附上python代码 #!/usr/bin/env python # _*_ coding:utf-8 _*_ fro ...

  3. Oracle EBS 物化视图

    怎么理解物化视图呢,先随意拿一个建物化视图的例子看一下. create materialized view EBS_ACCOUNTS_HIERARCHY_MV refresh complete on ...

  4. windows7环境下使用pip安装MySQLdb for python3.7

    1.首先,需要确定你已经安装了pip.在Python2.7的安装包中,easy_install.py和pip都是默认安装的.可以在Python的安装目录先确认,如果\Python37\Scripts里 ...

  5. Nlog.Config:日志方法步骤

    首先添加negut包Nlog.Config: 安装完毕以后,可以替换Nlog.config <?xml version="1.0" encoding="utf-8& ...

  6. 从零开始学习VoltDB

    1.什么是VoltDB? 是一个优化吞吐率的高性能集群开源SQLRDBMS(Database Management System),它是一个内存关系型数据库,既获得了nosql的良好可扩展性,高吞吐量 ...

  7. mysql host'XXX' is not allowed to connect to this mysql server

    错误的原因一般是没有添加 IP可远程的权限. 首先以 root 帐户登陆 MySQL 1.在 Windows 主机中点击开始菜单,运行,输入“cmd”,进入控制台,然后cd 进入MySQL 的 bin ...

  8. Django商城项目笔记No.5用户部分-注册接口-短信验证码

    Django商城项目笔记No.4用户部分-注册接口-短信验证码 短信验证码也保存在redis里(sms_code_15101234567) 在views中新增SMSCodeView类视图,并且写出步骤 ...

  9. Spring线程池配置模板设计(基于Springboot)

    目录 线程池配置模板 基础的注解解释 常用配置参数 配置类设计 线程池使用 ThreadPoolTaskExecutor源码 线程池配置模板 springboot给我们提供了一个线程池的实现,它的底层 ...

  10. loli的混合算法测试

    最近刚讲了最短路,说要考试我以为是考最短路,然而只有一道是最短路... 数据似乎有一点问题,不管了,反正手工测评都是对的,那现在就来看看题吧. Balanced:(此处并没有网址) 题意概述:$n$  ...