Mnist手写数字识别 Tensorflow

任务目标

  • 了解mnist数据集
  • 搭建和测试模型

编辑环境

操作系统:Win10

python版本:3.6

集成开发环境:pycharm

tensorflow版本:1.*


程序流程图

了解mnist数据集

mnist数据集:mnist数据集下载地址

  MNIST 数据集来自美国国家标准与技术研究所, National Institute of Standards and Technology (NIST). 训练集 (training set) 由来自 250 个不同人手写的数字构成, 其中 50% 是高中学生, 50% 来自人口普查局 (the Census Bureau) 的工作人员. 测试集(test set) 也是同样比例的手写数字数据.

  图片是以字节的形式进行存储, 我们需要把它们读取到 NumPy array 中, 以便训练和测试算法。

读取mnist数据集

  1. mnist = input_data.read_data_sets("mnist_data", one_hot=True)

模型结构

输入层

  1. with tf.variable_scope("data"):
  2. x = tf.placeholder(tf.float32,shape=[None,784],name='x_pred') # 784=28*28*1 宽长为28,单通道图片
  3. y_true = tf.placeholder(tf.int32,shape=[None,10]) # 10个类别

第一层卷积

  现在我们可以开始实现第一层了。它由一个卷积接一个max pooling完成。卷积在每个5x5的patch中算出32个特征。卷积的权重张量形状是[5, 5, 1, 32],前两个维度是patch的大小,接着是输入的通道数目,最后是输出的通道数目。 而对于每一个输出通道都有一个对应的偏置量。

为了用这一层,我们把x变成一个4d向量,其第2、第3维对应图片的宽、高,最后一维代表图片的颜色通道数(因为是灰度图所以这里的通道数为1,如果是rgb彩色图,则为3)。

我们把x_image和权值向量进行卷积,加上偏置项,然后应用ReLU激活函数,最后进行max pooling。

  1. with tf.variable_scope("conv1"):
  2. w_conv1 = tf.Variable(tf.random_normal([5,5,1,32])) # 5*5的卷积核 1个通道的输入图像 32个不同的卷积核,得到32个特征图
  3. b_conv1 = tf.Variable(tf.constant(0.0,shape=[32]))
  4. x_reshape = tf.reshape(x,[-1,28,28,1]) # n张 28*28 的单通道图片
  5. conv1 = tf.nn.relu(tf.nn.conv2d(x_reshape,w_conv1,strides=[1,1,1,1],padding="SAME")+b_conv1) #strides为过滤器步长 padding='SAME' 边缘自动补充
  6. pool1 = tf.nn.max_pool(conv1,ksize=[1,2,2,1],strides=[1,2,2,1],padding="SAME") # ksize为池化层过滤器的尺度,strides为过滤器步长 padding="SAME" 考虑边界,如果不够用 用0填充

第二层卷积

  为了构建一个更深的网络,我们会把几个类似的层堆叠起来。第二层中,每个5x5的patch会得到64个特征

  1. with tf.variable_scope("conv2"):
  2. w_conv2 = tf.Variable(tf.random_normal([5,5,32,64]))
  3. b_conv2 = tf.Variable(tf.constant(0.0,shape=[64]))
  4. conv2 = tf.nn.relu(tf.nn.conv2d(pool1,w_conv2,strides=[1,1,1,1],padding="SAME")+b_conv2)
  5. pool2 = tf.nn.max_pool(conv2,ksize=[1,2,2,1],strides=[1,2,2,1],padding="SAME")

密集连接层

  现在,图片尺寸减小到7x7,我们加入一个有1024个神经元的全连接层,用于处理整个图片。我们把池化层输出的张量reshape成一些向量,乘上权重矩阵,加上偏置,然后对其使用ReLU。

  为了减少过拟合,我们在输出层之前加入dropout。我们用一个placeholder来代表一个神经元的输出在dropout中保持不变的概率。这样我们可以在训练过程中启用dropout,在测试过程中关闭dropout。 TensorFlow的tf.nn.dropout操作除了可以屏蔽神经元的输出外,还会自动处理神经元输出值的scale。所以用dropout的时候可以不用考虑scale。

  1. with tf.variable_scope("fc1"):
  2. w_fc1 = tf.Variable(tf.random_normal([7*7*64,1024])) # 经过两次卷积和池化 28 * 28/(2+2) = 7 * 7
  3. b_fc1 = tf.Variable(tf.constant(0.0,shape=[1024]))
  4. h_pool2_flat = tf.reshape(pool2, [-1, 7 * 7 * 64])
  5. h_fc1 = tf.nn.relu(tf.matmul(h_pool2_flat, w_fc1) + b_fc1)
  6. # 在输出层之前加入dropout以减少过拟合
  7. keep_prob = tf.placeholder("float32",name="keep_prob")
  8. h_fc1_drop = tf.nn.dropout(h_fc1, keep_prob)

输出层

&emsp' 最后,我们添加一个softmax层,就像前面的单层softmax regression一样。

  1. with tf.variable_scope("fc2"):
  2. w_fc2 = tf.Variable(tf.random_normal([1024,10])) # 经过两次卷积和池化 28 * 28/(2+2) = 7 * 7
  3. b_fc2 = tf.Variable(tf.constant(0.0,shape=[10]))
  4. y_predict = tf.matmul(h_fc1_drop,w_fc2)+b_fc2
  5. tf.add_to_collection('pred_network', y_predict) # 用于加载模型获取要预测的网络结构

训练和评估模型

  为了进行训练和评估,我们使用与之前简单的单层SoftMax神经网络模型几乎相同的一套代码,只是我们会用更加复杂的ADAM优化器来做梯度最速下降,在feed_dict中加入额外的参数keep_prob来控制dropout比例。然后每100次迭代输出一次日志。

  1. with tf.variable_scope("loss"):
  2. loss = tf.reduce_mean(tf.nn.softmax_cross_entropy_with_logits(labels=y_true,logits=y_predict))
  3. with tf.variable_scope("optimizer"):
  4. # 使用反向传播,利用优化器使损失函数最小化
  5. train_op = tf.train.AdamOptimizer(0.001).minimize(loss)
  6. with tf.variable_scope("acc"):
  7. # 检测我们的预测是否真实标签匹配(索引位置一样表示匹配)
  8. # tf.argmax(y_conv,dimension), 返回最大数值的下标 通常和tf.equal()一起使用,计算模型准确度
  9. # dimension=0 按列找 dimension=1 按行找
  10. equal_list = tf.equal(tf.arg_max(y_true,1),tf.arg_max(y_predict,1))
  11. # 统计测试准确率, 将correct_prediction的布尔值转换为浮点数来代表对、错,并取平均值。
  12. accuracy = tf.reduce_mean(tf.cast(equal_list,tf.float32))
  13. # tensorboard
  14. # tf.summary.histogram用来显示直方图信息
  15. # tf.summary.scalar用来显示标量信息
  16. # Summary:所有需要在TensorBoard上展示的统计结果
  17. tf.summary.histogram("weight",w_fc2)
  18. tf.summary.histogram("bias",b_fc2)
  19. tf.summary.scalar("loss",loss)
  20. tf.summary.scalar("acc",accuracy)
  21. merged = tf.summary.merge_all()
  22. saver = tf.train.Saver()
  23. with tf.Session() as sess:
  24. sess.run(tf.global_variables_initializer())
  25. filewriter = tf.summary.FileWriter("tfboard",graph=sess.graph)
  26. if is_train: # 训练
  27. for i in range(20001):
  28. x_train, y_train = mnist.train.next_batch(50)
  29. if i%100==0:
  30. # 评估模型准确度,此阶段不使用Dropout
  31. print("第%d训练,准确率为%f" % (i + 1, sess.run(accuracy, feed_dict={x: x_train, y_true: y_train, keep_prob: 1.0})))
  32. # # 训练模型,此阶段使用50%的Dropout
  33. sess.run(train_op,feed_dict={x:x_train,y_true:y_train,keep_prob: 0.5})
  34. summary = sess.run(merged,feed_dict={x:x_train,y_true:y_train, keep_prob: 1})
  35. filewriter.add_summary(summary,i)
  36. saver.save(sess,savemodel)
  37. else: # 测试集预测
  38. count = 0.0
  39. epochs = 300
  40. saver.restore(sess, savemodel)
  41. for i in range(epochs):
  42. x_test, y_test = mnist.train.next_batch(1)
  43. print("第%d张图片,真实值为:%d预测值为:%d" % (i + 1,
  44. tf.argmax(sess.run(y_true, feed_dict={x: x_test, y_true: y_test,keep_prob: 1.0}),
  45. 1).eval(),
  46. tf.argmax(
  47. sess.run(y_predict, feed_dict={x: x_test, y_true: y_test,keep_prob: 1.0}),
  48. 1).eval()
  49. ))
  50. if (tf.argmax(sess.run(y_true, feed_dict={x: x_test, y_true: y_test,keep_prob: 1.0}), 1).eval() == tf.argmax(
  51. sess.run(y_predict, feed_dict={x: x_test, y_true: y_test,keep_prob: 1.0}), 1).eval()):
  52. count = count + 1
  53. print("正确率为 %.2f " % float(count * 100 / epochs) + "%")

评估结果

传入手写图片,利用模型预测

  首先利用opencv包将图片转为单通道(灰度图),调整图像尺寸28*28,并且二值化图像,通过处理最后得到一个(0~1)扁平的图片像素值(一个二维数组)。

手写数字图片



处理手写数字图片

  1. def dealFigureImg(imgPath):
  2. img = cv2.imread(imgPath) # 手写数字图像所在位置
  3. img = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY) # 转换图像为单通道(灰度图)
  4. resize_img = cv2.resize(img, (28, 28)) # 调整图像尺寸为28*28
  5. ret, thresh_img = cv2.threshold(resize_img, 127, 255, cv2.THRESH_BINARY) # 二值化
  6. cv2.imwrite("image/temp.jpg",thresh_img)
  7. im = Image.open('image/temp.jpg')
  8. data = list(im.getdata()) # 得到一个扁平的 图片像素
  9. result = [(255 - x) * 1.0 / 255.0 for x in data] # 像素值范围(0-255),转换为(0-1) ->符合模型训练时传入数据的值
  10. result = np.expand_dims(result, 0) # 扩展维度 ->符合模型训练时传入数据的维度
  11. os.remove('image/temp.jpg')
  12. return result

载入模型进行预测

  1. def predictFigureImg(imgPath):
  2. result = dealFigureImg(imgPath)
  3. with tf.Session() as sess:
  4. new_saver = tf.train.import_meta_graph("model/mnist_model.meta")
  5. new_saver.restore(sess, "model/mnist_model")
  6. graph = tf.get_default_graph()
  7. x = graph.get_operation_by_name('data/x_pred').outputs[0]
  8. keep_prob = graph.get_operation_by_name('fc1/keep_prob').outputs[0]
  9. y = tf.get_collection("pred_network")[0]
  10. predict = np.argmax(sess.run(y, feed_dict={x: result,keep_prob:1.0}))
  11. print("result:",predict)

预测结果

完整代码

  1. import tensorflow as tf
  2. import cv2
  3. import os
  4. import numpy as np
  5. from PIL import Image
  6. from tensorflow.examples.tutorials.mnist import input_data
  7. # 构造模型
  8. def getMnistModel(savemodel,is_train):
  9. """
  10. :param savemodel: 模型保存路径
  11. :param is_train: True为训练,False为测试模型
  12. :return:None
  13. """
  14. mnist = input_data.read_data_sets("mnist_data", one_hot=True)
  15. with tf.variable_scope("data"):
  16. x = tf.placeholder(tf.float32,shape=[None,784],name='x_pred') # 784=28*28*1 宽长为28,单通道图片
  17. y_true = tf.placeholder(tf.int32,shape=[None,10]) # 10个类别
  18. with tf.variable_scope("conv1"):
  19. w_conv1 = tf.Variable(tf.random_normal([5,5,1,32])) # 5*5的卷积核 1个通道的输入图像 32个不同的卷积核,得到32个特征图
  20. b_conv1 = tf.Variable(tf.constant(0.0,shape=[32]))
  21. x_reshape = tf.reshape(x,[-1,28,28,1]) # n张 28*28 的单通道图片
  22. conv1 = tf.nn.relu(tf.nn.conv2d(x_reshape,w_conv1,strides=[1,1,1,1],padding="SAME")+b_conv1) #strides为过滤器步长 padding='SAME' 边缘自动补充
  23. pool1 = tf.nn.max_pool(conv1,ksize=[1,2,2,1],strides=[1,2,2,1],padding="SAME") # ksize为池化层过滤器的尺度,strides为过滤器步长 padding="SAME" 考虑边界,如果不够用 用0填充
  24. with tf.variable_scope("conv2"):
  25. w_conv2 = tf.Variable(tf.random_normal([5,5,32,64]))
  26. b_conv2 = tf.Variable(tf.constant(0.0,shape=[64]))
  27. conv2 = tf.nn.relu(tf.nn.conv2d(pool1,w_conv2,strides=[1,1,1,1],padding="SAME")+b_conv2)
  28. pool2 = tf.nn.max_pool(conv2,ksize=[1,2,2,1],strides=[1,2,2,1],padding="SAME")
  29. with tf.variable_scope("fc1"):
  30. w_fc1 = tf.Variable(tf.random_normal([7*7*64,1024])) # 经过两次卷积和池化 28 * 28/(2+2) = 7 * 7
  31. b_fc1 = tf.Variable(tf.constant(0.0,shape=[1024]))
  32. h_pool2_flat = tf.reshape(pool2, [-1, 7 * 7 * 64])
  33. h_fc1 = tf.nn.relu(tf.matmul(h_pool2_flat, w_fc1) + b_fc1)
  34. # 在输出层之前加入dropout以减少过拟合
  35. keep_prob = tf.placeholder("float32",name="keep_prob")
  36. h_fc1_drop = tf.nn.dropout(h_fc1, keep_prob)
  37. with tf.variable_scope("fc2"):
  38. w_fc2 = tf.Variable(tf.random_normal([1024,10])) # 经过两次卷积和池化 28 * 28/(2+2) = 7 * 7
  39. b_fc2 = tf.Variable(tf.constant(0.0,shape=[10]))
  40. y_predict = tf.matmul(h_fc1_drop,w_fc2)+b_fc2
  41. tf.add_to_collection('pred_network', y_predict) # 用于加载模型获取要预测的网络结构
  42. with tf.variable_scope("loss"):
  43. loss = tf.reduce_mean(tf.nn.softmax_cross_entropy_with_logits(labels=y_true,logits=y_predict))
  44. with tf.variable_scope("optimizer"):
  45. # 使用反向传播,利用优化器使损失函数最小化
  46. train_op = tf.train.AdamOptimizer(0.001).minimize(loss)
  47. with tf.variable_scope("acc"):
  48. # 检测我们的预测是否真实标签匹配(索引位置一样表示匹配)
  49. # tf.argmax(y_conv,dimension), 返回最大数值的下标 通常和tf.equal()一起使用,计算模型准确度
  50. # dimension=0 按列找 dimension=1 按行找
  51. equal_list = tf.equal(tf.arg_max(y_true,1),tf.arg_max(y_predict,1))
  52. # 统计测试准确率, 将correct_prediction的布尔值转换为浮点数来代表对、错,并取平均值。
  53. accuracy = tf.reduce_mean(tf.cast(equal_list,tf.float32))
  54. # tensorboard
  55. # tf.summary.histogram用来显示直方图信息
  56. # tf.summary.scalar用来显示标量信息
  57. # Summary:所有需要在TensorBoard上展示的统计结果
  58. tf.summary.histogram("weight",w_fc2)
  59. tf.summary.histogram("bias",b_fc2)
  60. tf.summary.scalar("loss",loss)
  61. tf.summary.scalar("acc",accuracy)
  62. merged = tf.summary.merge_all()
  63. saver = tf.train.Saver()
  64. with tf.Session() as sess:
  65. sess.run(tf.global_variables_initializer())
  66. filewriter = tf.summary.FileWriter("tfboard",graph=sess.graph)
  67. if is_train: # 训练
  68. for i in range(20001):
  69. x_train, y_train = mnist.train.next_batch(50)
  70. if i%100==0:
  71. # 评估模型准确度,此阶段不使用Dropout
  72. print("第%d训练,准确率为%f" % (i + 1, sess.run(accuracy, feed_dict={x: x_train, y_true: y_train, keep_prob: 1.0})))
  73. # # 训练模型,此阶段使用50%的Dropout
  74. sess.run(train_op,feed_dict={x:x_train,y_true:y_train,keep_prob: 0.5})
  75. summary = sess.run(merged,feed_dict={x:x_train,y_true:y_train, keep_prob: 1})
  76. filewriter.add_summary(summary,i)
  77. saver.save(sess,savemodel)
  78. else: # 测试集预测
  79. count = 0.0
  80. epochs = 300
  81. saver.restore(sess, savemodel)
  82. for i in range(epochs):
  83. x_test, y_test = mnist.train.next_batch(1)
  84. print("第%d张图片,真实值为:%d预测值为:%d" % (i + 1,
  85. tf.argmax(sess.run(y_true, feed_dict={x: x_test, y_true: y_test,keep_prob: 1.0}),
  86. 1).eval(),
  87. tf.argmax(
  88. sess.run(y_predict, feed_dict={x: x_test, y_true: y_test,keep_prob: 1.0}),
  89. 1).eval()
  90. ))
  91. if (tf.argmax(sess.run(y_true, feed_dict={x: x_test, y_true: y_test,keep_prob: 1.0}), 1).eval() == tf.argmax(
  92. sess.run(y_predict, feed_dict={x: x_test, y_true: y_test,keep_prob: 1.0}), 1).eval()):
  93. count = count + 1
  94. print("正确率为 %.2f " % float(count * 100 / epochs) + "%")
  95. # 手写数字图像预测
  96. def dealFigureImg(imgPath):
  97. img = cv2.imread(imgPath) # 手写数字图像所在位置
  98. img = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY) # 转换图像为单通道(灰度图)
  99. resize_img = cv2.resize(img, (28, 28)) # 调整图像尺寸为28*28
  100. ret, thresh_img = cv2.threshold(resize_img, 127, 255, cv2.THRESH_BINARY) # 二值化
  101. cv2.imwrite("image/temp.jpg",thresh_img)
  102. im = Image.open('image/temp.jpg')
  103. data = list(im.getdata()) # 得到一个扁平的 图片像素
  104. result = [(255 - x) * 1.0 / 255.0 for x in data] # 像素值范围(0-255),转换为(0-1) ->符合模型训练时传入数据的值
  105. result = np.expand_dims(result, 0) # 扩展维度 ->符合模型训练时传入数据的维度
  106. os.remove('image/temp.jpg')
  107. return result
  108. def predictFigureImg(imgPath):
  109. result = dealFigureImg(imgPath)
  110. with tf.Session() as sess:
  111. new_saver = tf.train.import_meta_graph("model/mnist_model.meta")
  112. new_saver.restore(sess, "model/mnist_model")
  113. graph = tf.get_default_graph()
  114. x = graph.get_operation_by_name('data/x_pred').outputs[0]
  115. keep_prob = graph.get_operation_by_name('fc1/keep_prob').outputs[0]
  116. y = tf.get_collection("pred_network")[0]
  117. predict = np.argmax(sess.run(y, feed_dict={x: result,keep_prob:1.0}))
  118. print("result:",predict)
  119. if __name__ == '__main__':
  120. # 训练和预测
  121. modelPath = "model/mnist_model"
  122. getMnistModel(modelPath,True) # True 训练 False 预测
  123. # 图片传入模型 进行预测
  124. # imgPath = "image/8.jpg"
  125. # predictFigureImg(imgPath)

Mnist手写数字识别 Tensorflow的更多相关文章

  1. MNIST手写数字识别 Tensorflow实现

    def conv2d(x, W): return tf.nn.conv2d(x, W, strides=[1, 1, 1, 1], padding='SAME') 1. strides在官方定义中是一 ...

  2. Android+TensorFlow+CNN+MNIST 手写数字识别实现

    Android+TensorFlow+CNN+MNIST 手写数字识别实现 SkySeraph 2018 Email:skyseraph00#163.com 更多精彩请直接访问SkySeraph个人站 ...

  3. 基于tensorflow的MNIST手写数字识别(二)--入门篇

    http://www.jianshu.com/p/4195577585e6 基于tensorflow的MNIST手写字识别(一)--白话卷积神经网络模型 基于tensorflow的MNIST手写数字识 ...

  4. Tensorflow之MNIST手写数字识别:分类问题(1)

    一.MNIST数据集读取 one hot 独热编码独热编码是一种稀疏向量,其中:一个向量设为1,其他元素均设为0.独热编码常用于表示拥有有限个可能值的字符串或标识符优点:   1.将离散特征的取值扩展 ...

  5. TensorFlow——MNIST手写数字识别

    MNIST手写数字识别 MNIST数据集介绍和下载:http://yann.lecun.com/exdb/mnist/   一.数据集介绍: MNIST是一个入门级的计算机视觉数据集 下载下来的数据集 ...

  6. 基于TensorFlow的MNIST手写数字识别-初级

    一:MNIST数据集    下载地址 MNIST是一个包含很多手写数字图片的数据集,一共4个二进制压缩文件 分别是test set images,test set labels,training se ...

  7. Tensorflow实现MNIST手写数字识别

    之前我们讲了神经网络的起源.单层神经网络.多层神经网络的搭建过程.搭建时要注意到的具体问题.以及解决这些问题的具体方法.本文将通过一个经典的案例:MNIST手写数字识别,以代码的形式来为大家梳理一遍神 ...

  8. mnist手写数字识别——深度学习入门项目(tensorflow+keras+Sequential模型)

    前言 今天记录一下深度学习的另外一个入门项目——<mnist数据集手写数字识别>,这是一个入门必备的学习案例,主要使用了tensorflow下的keras网络结构的Sequential模型 ...

  9. mnist 手写数字识别

    mnist 手写数字识别三大步骤 1.定义分类模型2.训练模型3.评价模型 import tensorflow as tfimport input_datamnist = input_data.rea ...

随机推荐

  1. SpringMVC面试专题

    SpringMVC面试专题 1. 简单的谈一下SpringMVC的工作流程? 流程 1.用户发送请求至前端控制器DispatcherServlet 2.DispatcherServlet收到请求调用H ...

  2. Redis面试专题

    Redis面试专题 1. 什么是redis? Redis 是一个基于内存的高性能key-value数据库. (有空再补充,有理解错误或不足欢迎指正) 2. Reids的特点 Redis本质上是一个Ke ...

  3. Java前端面试题总结

    Java前端面试题总结 简单说一下HTML,CSS,javaScript在网页开发中的定位? HTML:超文本标记语言,定义网页的结构 CSS:层叠样式表,用来美化页面 JavaScript:主要用来 ...

  4. android自定义控件onLayout方法

    onLayout设置子控件的位置,对应一些普通的控件例如Button.TextView等控件,不存在子控件,所以可以不用复写该方法. 向线性布局.相对布局等存在子控件,可以覆写该方法去控制子控件的位置 ...

  5. React实战教程之从零开始手把手教你使用 React 最新特性Hooks API 打造一款计算机知识测验App

    项目演示地址 项目演示地址 项目代码结构 前言 React 框架的优雅不言而喻,组件化的编程思想使得React框架开发的项目代码简洁,易懂,但早期 React 类组件的写法略显繁琐.React Hoo ...

  6. 僵尸扫描-scapy、nmap

    如果不知道僵尸扫描是什么,请参考我的这篇博客 实验环境: kali(攻击者) 192.168.0.103 metasploitable2(目标主机) 192.168.0.104 win xp sp2( ...

  7. ThinkPHP5生成二维码图片与另一张背景图片进行合成

    1.PHP方法 public function do_qrcode(){ Vendor('Qrcode.phpqrcode'); Vendor('Qrcode.Compress'); $object ...

  8. APP测试之内存命令查询

    CPU占有率            adb shell dumpsys cpuinfo :获取本机CPU占有率            adb shell dumpsys  cpuinfo | find ...

  9. WPF中的Data Binding调试指南

    大家平时做WPF开发,相信用Visual studio的小伙伴比较多.XAML里面曾经在某些特殊版本的Visual Studio中是可以加断点进行调试的,不过目前多数版本都不支持在XAML加断点来调试 ...

  10. spring quartz 每30分钟执行一次cronExpression表达式怎么写

      <cron-expression>0 0/30 * * * ?</cron-expression>:每隔30分钟 <cron-expression>0 0/15 ...