tensorflow训练mnist数据集——卷积神经网络(代码片段)

laishenghao laishenghao     2023-01-04     209

关键词:

 

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

 

1、模型基本结构

  如下图所示,本次采用的模型共有8层(包含dropout层)。其中卷积层和池化层各有两层。

  在整个模型中,输入层负责数据输入;卷积层负责提取图片的特征;池化层采用最大池化的方式,突出主要特征,并减少参数维度;全连接层再将个特征组合起来;dropout层可以减少每次训练的计算量,并可以一定程度上避免过拟合问题;最后输出层再综合各特征数据,得出最终结果。

  Dropout层起始并没有增加训练参数,只是随机的将某些节点间的连接弧断开,使其在本次中暂时的不参与训练。

技术分享图片

2、数据预处理

  首先读取用于训练的数据。

from tensorflow.examples.tutorials.mnist import input_data

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

  在前面的输入层中,输入的每个样本都是一维的数据,而卷积神经网络的样本数据将是多维的。因此我们需要将读取到的数据再reshape一下,使其符合要求。

data.reshape([batchSize, 28, 28, 1])

 

3、输入层

  输入层的shape为:bitchSize * 28 * 28 * 1,第一个参数表示每个mini-batch的样本数量,由传入None可以让TensorFlow自动推断;后面三个参数表示每个样本的高为28,宽为28,通道数为1。

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

 

4、卷积层

  第一个卷积层的卷积核大小为5 * 5,数量为32个。padding方式采用‘SAME’。第二个卷积层类似,只是通道数,输出维度不一样。

1 convFilter1 = tf.Variable(tf.truncated_normal([5, 5, 1, 32], mean=0, stddev=0.1))
2 convBias1   = tf.Variable(tf.truncated_normal([32], mean=0, stddev=0.1))
3 convLayer1  = tf.nn.conv2d(input=inputLayer, filter=convFilter1, strides=[1, 1, 1, 1], padding=SAME)
4 convLayer1  = tf.add(convLayer1, convBias1)
5 convLayer1  = tf.nn.relu(convLayer1)

 

5、池化层

  滑动窗口的大小为 2 * 2,在高和宽的维度上的滑动步幅也为2,其他维度为1。本模型中第二个池化层与第一个池化层一样。

poolLayer1 = tf.nn.max_pool(value=convLayer1, ksize=[1, 2, 2, 1], strides=[1, 2, 2, 1], padding=SAME)

 

 6、全连接层

  全连接层将前面在每个样本中提取到的多维特征展开成一维,作为全连接层的输入。

1 fullWeight = tf.Variable(tf.truncated_normal(shape=[7 * 7 * 64, 1024], mean=0, stddev=0.1))
2 fullBias   = tf.Variable(tf.truncated_normal(shape=[1024], mean=0.0, stddev=0.1))
3 fullInput  = tf.reshape(poolLayer2, [-1, 7 * 7 * 64])
4 fullLayer  = tf.add(tf.matmul(fullInput, fullWeight), fullBias)
5 fullLayer  = tf.nn.relu(fullLayer)

 

7、Dropout层

  dropout层可以防止过拟合问题。这里指定的保留率为0.8。

dropLayer = tf.nn.dropout(fullLayer, keep_prob=0.8)

 

8、输出层

  最终输出10个数字的分类。

1 outputWeight = tf.Variable(tf.truncated_normal(shape=[1024, 10], mean=0.0, stddev=0.1))
2 outputBias   = tf.Variable(tf.truncated_normal(shape=[10], mean=0, stddev=0.1))
3 outputLayer  = tf.add(tf.matmul(dropLayer, outputWeight), outputBias)

 

  模型的其他部分与前面的多层神经网络差不多,这里不再赘述。

 

9、模型在训练集与测试集上的表现

  从模型图上可以看到,本次采用的模型的复杂度比前面的多层神经网络高很多。正因如此,每次迭代计算也比前面的耗时的多,后者单次耗时为前者的1500多倍。可见虽然只增加了几层(当然除了层数的增加还有节点数的增加),但增加的计算量非常的多。

  下面两张图为卷积神经网络前面部分和后面部分迭代的输出结果,可以发现到最后卷积神经网络在训练集上已经接近100%的准确率。

技术分享图片

技术分享图片

 

  在测试集上的准确率也达到了 98% 99%,比多层神经网络提供了约2个百分点。

技术分享图片

 

附:

  完整代码如下:

技术分享图片
 1 import tensorflow as tf
 2 from tensorflow.examples.tutorials.mnist import input_data
 3 import time
 4 
 5 # 读取数据
 6 mnist = input_data.read_data_sets(./data/mnist, one_hot=True)
 7 
 8 # 输入层
 9 inputLayer = tf.placeholder(tf.float32, shape=[None, 28, 28, 1])
10 
11 # 卷积层(1)
12 convFilter1 = tf.Variable(tf.truncated_normal([5, 5, 1, 32], mean=0, stddev=0.1))
13 convBias1   = tf.Variable(tf.truncated_normal([32], mean=0, stddev=0.1))
14 convLayer1  = tf.nn.conv2d(input=inputLayer, filter=convFilter1, strides=[1, 1, 1, 1], padding=SAME)
15 convLayer1  = tf.add(convLayer1, convBias1)
16 convLayer1  = tf.nn.relu(convLayer1)
17 
18 # 池化层(1)
19 poolLayer1 = tf.nn.max_pool(value=convLayer1, ksize=[1, 2, 2, 1], strides=[1, 2, 2, 1], padding=SAME)
20 
21 # 卷积层(2)
22 convFilter2 = tf.Variable(tf.truncated_normal([5, 5, 32, 64], mean=0, stddev=0.1))
23 convBias2   = tf.Variable(tf.truncated_normal([64], mean=0, stddev=0.1))
24 convLayer2  = tf.nn.conv2d(input=poolLayer1, filter=convFilter2, strides=[1, 1, 1, 1], padding=SAME)
25 convLayer2  = tf.add(convLayer2, convBias2)
26 convLayer2  = tf.nn.relu(convLayer2)
27 
28 # 池化层(2)
29 poolLayer2 = tf.nn.max_pool(value=convLayer2, ksize=[1, 2, 2, 1], strides=[1, 2, 2, 1], padding=SAME)
30 
31 # 全连接层
32 fullWeight = tf.Variable(tf.truncated_normal(shape=[7 * 7 * 64, 1024], mean=0, stddev=0.1))
33 fullBias   = tf.Variable(tf.truncated_normal(shape=[1024], mean=0.0, stddev=0.1))
34 fullInput  = tf.reshape(poolLayer2, [-1, 7 * 7 * 64])
35 fullLayer  = tf.add(tf.matmul(fullInput, fullWeight), fullBias)
36 fullLayer  = tf.nn.relu(fullLayer)
37 
38 # dropout层
39 dropLayer = tf.nn.dropout(fullLayer, keep_prob=0.8)
40 
41 # 输出层
42 outputWeight = tf.Variable(tf.truncated_normal(shape=[1024, 10], mean=0.0, stddev=0.1))
43 outputBias   = tf.Variable(tf.truncated_normal(shape=[10], mean=0, stddev=0.1))
44 outputLayer  = tf.add(tf.matmul(dropLayer, outputWeight), outputBias)
45 
46 # 标签
47 outputLabel = tf.placeholder(tf.float32, shape=[None, 10])
48 
49 # 损失函数及目标函数
50 loss   = tf.reduce_mean(tf.nn.softmax_cross_entropy_with_logits_v2(labels=outputLabel, logits=outputLayer))
51 target = tf.train.AdamOptimizer().minimize(loss)
52 
53 # 记录起始训练时间
54 startTime = time.time()
55 
56 # 训练
57 with tf.Session() as sess:
58     sess.run(tf.global_variables_initializer())
59     batchSize = 64
60     for i in range(1000):
61         batch = mnist.train.next_batch(batchSize)
62         inputData = batch[0].reshape([batchSize, 28, 28, 1])
63         labelData = batch[1]
64         sess.run([target, loss], feed_dict=inputLayer: inputData, outputLabel: labelData)
65 
66         corrected = tf.equal(tf.argmax(outputLabel, 1), tf.argmax(outputLayer, 1))
67         accuracy = tf.reduce_mean(tf.cast(corrected, tf.float32))
68         accuracyValue = sess.run(accuracy, feed_dict=inputLayer: inputData, outputLabel: labelData)
69         print(i, train set accuracy:, accuracyValue)
70 
71     # 打印结束时间
72     endTime = time.time()
73     print(train time:, endTime - startTime)
74 
75     # 测试
76     corrected  = tf.equal(tf.argmax(outputLabel, 1), tf.argmax(outputLayer, 1))
77     accuracy   = tf.reduce_mean(tf.cast(corrected, tf.float32))
78     testImages = mnist.test.images.reshape([-1, 28, 28, 1])
79     testLabels = mnist.test.labels
80     accuracyValue = sess.run(accuracy, feed_dict=inputLayer: testImages, outputLabel: testLabels)
81     print("accuracy on test set:", accuracyValue)
82 
83     sess.close()
View Code

 

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

 

吴裕雄python神经网络——tensorflow使用卷积神经网络训练和预测mnist手写数据集(代码片段)

importtensorflowastfimportnumpyasnpfromtensorflow.examples.tutorials.mnistimportinput_data#设置输入参数batch_size=128test_size=256#初始化权值与定义网络结构,建构一个3个卷积层和3个池化层,一个全连接层和一个输出层的卷积神经网络#首先定义初始化... 查看详情

tensorflow/简单网络mnist数据集-softmax全连接神经网络,卷积神经网络模型(代码片段)

初学tensorflow,参考了以下几篇博客:soft模型 tensorflow构建全连接神经网络tensorflow构建卷积神经网络tensorflow构建卷积神经网络tensorflow构建CNN[待学习]全连接+各种优化[待学习]BN层[待学习]先解释以下MNIST数据集,训练数据集有5... 查看详情

深度学习与tensorflow2.0卷积神经网络(cnn)(代码片段)

注:在很长一段时间,MNIST数据集都是机器学习界很多分类算法的benchmark。初学深度学习,在这个数据集上训练一个有效的卷积神经网络就相当于学习编程的时候打印出一行“HelloWorld!”。下面基于与MNIST数据集非常类似的... 查看详情

tensorflow实战计算机视觉之mnist数据集

计算机视觉方向使用深度学习主要是卷积神经网络,可以参考这篇文章:零基础入门深度学习(4)-卷积神经网络MNIST机器学习入门:http://www.tensorfly.cn/tfdoc/tutorials/mnist_beginners.html卷积神经网络改善MNIST数据集识别准确率M... 查看详情

tensorflow可视化mnist手写数字训练(代码片段)

【简述】  我们在学习编程语言时,往往第一个程序就是打印“HelloWorld”,那么对于人工智能学习系统平台来说,他的“HelloWorld”小程序就是MNIST手写数字训练了。MNIST是一个手写数字的数据集,官网是YannLeCun‘sw... 查看详情

深度学习基于tensorflow的服装图像分类训练(数据集:fashion-mnist)(代码片段)

...习挑战赛目录前言了解Fashion-MNIST数据集下载数据集使用tensorflow下载(推荐)数据集分类数据集格式采用CPU训练还是GPU训练区别使用CPU训练使用GPU训练预处理最值归一化(normalization)升级图片维度显示部分图片建... 查看详情

tensorflow2手把手教你训练mnist数据集part1(代码片段)

TensorFlow2手把手教你训练MNIST数据集part1概述get_data函数pre_processing函数main函数完整代码概述MNIST包含0~9的手写数字,共有60000个训练集和10000个测试集.数据的格式为单通道28*28的灰度图.get_data函数defget_data():"""读取数据:return... 查看详情

学习笔记tf057:tensorflowmnist,卷积神经网络循环神经网络无监督学习

MNIST卷积神经网络。https://github.com/nlintz/TensorFlow-Tutorials/blob/master/05_convolutional_net.py。TensorFlow搭建卷积神经网络(CNN)模型,训练MNIST数据集。构建模型。定义输入数据,预处理数据。读取数据MNIST,得到训练集图片、标记矩阵,测... 查看详情

基于tensorflow的cnn卷积神经网络对fasion-mnist数据集的分类器(代码片段)

写一个基于tensorflow的cnn,分类fasion-MNIST数据集这个就是fasion-mnist数据集了先上代码,在分析:importtensorflowastfimportpandasaspdimportnumpyasnpconfig=tf.ConfigProto()config.gpu_options.per_process_gpu_memory_fraction=0.3train_ 查看详情

tensorflow训练mnist——softmax单层神经网络(代码片段)

 1、MNIST数据集简介  首先通过下面两行代码获取到TensorFlow内置的MNIST数据集:fromtensorflow.examples.tutorials.mnistimportinput_datamnist=input_data.read_data_sets(‘./data/mnist‘,one_hot=True)  MNIST数据集共有55000(mnist.train. 查看详情

用pytorch对以mnist数据集进行卷积神经网络(代码片段)

...义优化算法\\colorred定义优化算法定义优化算法;迭代训练\\colorred迭代训练迭代训练&# 查看详情

基于tensorflow2.x实现多层卷积神经网络,实践mnist手写数字识别(代码片段)

一、MNIST数据集上篇文章中使用了Tensorflow2.x搭建了对层的BP神经网络,经过训练后发现准确率只有96.8%对于单环境的图片识别场景来说,还是有点偏低,本文使用多层的卷积代替BP网络中的隐藏层对模型进行优化。下面... 查看详情

用tensorflow搭建简单神经网络测试iris数据集和mnist数据集(代码片段)

1.步骤第一步:import相关模块,如importtensorflowastf第二步:指定输入网络的训练集和测试集,如指定训练集的输入x_train和标签y_train,测试集的输入x_test和标签y_test。 第三步:逐层搭建网络结构,model=tf.keras.models.Sequential()。&n... 查看详情

吴裕雄python神经网络——tensorflow实现回归模型训练预测mnist手写数据集(代码片段)

importtensorflowastffromtensorflow.examples.tutorials.mnistimportinput_datamnist=input_data.read_data_sets("E:\\\\MNIST_data\\\\",one_hot=True)#构建回归模型,输入原始真实值(grouptruth),采用sotfmax函数拟合,并定义损失函数和优化器#定义回 查看详情

tensorflow-实现knn算法-识别mnist数据集(代码片段)

...值和真实值相等的数据/所有测试数据)实现代码importtensorflowastffromtensorflow.examples.tutorials.mnistimportinput_dataimportnumpyasnpdefknn_tensorflow():"""tensorflow实现knn算法,对mnist数据识别分类:returnNone"""mn 查看详情

tensorflow-实现knn算法-识别mnist数据集(代码片段)

...值和真实值相等的数据/所有测试数据)实现代码importtensorflowastffromtensorflow.examples.tutorials.mnistimportinput_dataimportnumpyasnpdefknn_tensorflow():"""tensorflow实现knn算法,对mnist数据识别分类:returnNone"""mn 查看详情

ternsorflow学习:006-mnist进阶深入mnist(代码片段)

...人学习观看。没有看过MNIST基础的人请移步这里深入MNISTTensorFlow是一个非常强大的用来做大规模数值计算的库。其所擅长的任务之一就是实现以及训练深度神经网络。在本教程中,我们将学到构建一个TensorFlow模型的基本步骤,并... 查看详情

使用caffe训练mnist数据集-caffe教程实战

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