博主原文链接:用TensorFlow教你做手写字识别(准确率94.09%)

如需转载,请备注出处及链接,谢谢。

2012 年,Alex Krizhevsky, Geoff Hinton, and Ilya Sutskever 赢得 ImageNet 挑战赛冠军,基于CNN的图像识别开始受到普遍关注,CNN 成为了图像分类的黄金标准,自那以后,科学界掀开了基于深度神经网络对图像识别的大探索,现如今,深度学习对图像的识别能力已经超出了人眼的辨别能力。本公众号的图像识别系列将循序渐进,层层深入的带领读者去学习图像识别,本篇中笔者将带领读者一块完成基于CNN的手写数字图像识别。

工具要求

工具及环境要求如下,如果大家在安装TensorFlow过程遇到问题,可以咨询笔者一起探讨。

  • Python 2.7.14

  • TensorFlow 1.5

  • pip 10.0.1

  • linux环境

MNIST数据集

基于MNIST数据集实现手写字识别可谓是深度学习经典入门必会的技能,该数据集由60000张训练图片和10000张测试图片组成,每张均为28*28像素的黑白图片。关于数据集的获取,大家可以直接登录到官网(http://yann.lecun.com/exdb/mnist/)下载图1中4个压缩文件,或者关注本公众号后台回复“mnist数据集”获取,这里需要注意的是,下载后的数据集为二进制的。

图1 MNIST数据集

备注:笔者在网上看了不少相关文章,都提到要先用input_data.py代码对数据集进行转换,其实不必再单独找到源代码进行处理,直接按照文中代码即可进行处理测试。当然,如果大家实在按捺不住内心的小宇宙,可以粘贴“input_data.py”到公众号后台进行留言获取。

模型训练

CNN网络的训练代码如下,通过运行代码,(1)自动的完成训练数据集的下载,数据下载至代码所在目录的MNIST_data文件夹下。(2)自动保存训练模型,将模型保存在./ckpt_dir文件夹下。(3)自动在上次训练的基础上进行模型的训练。注意:脚本需要传入一个参数作为CNN网络的训练次数,当传入的参数为0是,默认训练1000次。笔者在做的时候训练了16000次,其实笔者在训练12560次的时候测试了一下识别效果,表现已经很不错了,如果大家想进一步提高准确率建议进一步提高训练次数或者丰富数据集等。不多说了,直接上代码:

  1. # -*- coding: utf-8 -*-
    import tensorflow as tf
    import tensorflow.examples.tutorials.mnist.input_data as input_data
    import os
  2. mnist = input_data.read_data_sets('MNIST_data', one_hot=True)
  3. x = tf.placeholder("float", shape=[None, 784])
    y_ = tf.placeholder("float", shape=[None, 10])
  4. W = tf.Variable(tf.zeros([784,10]))
    b = tf.Variable(tf.zeros([10]))
  5. def weight_variable(shape):
     initial = tf.truncated_normal(shape, stddev=0.1)
     return tf.Variable(initial)
  6. def bias_variable(shape):
     initial = tf.constant(0.1, shape=shape)
     return tf.Variable(initial)
  7. #权重初始化
    def conv2d(x, W):
     return tf.nn.conv2d(x, W, strides=[1, 1, 1, 1], padding='SAME')
  8. def max_pool_2x2(x):
     return tf.nn.max_pool(x, ksize=[1, 2, 2, 1],
                           strides=[1, 2, 2, 1], padding='SAME')
  9. #第一层卷积
    W_conv1 = weight_variable([5, 5, 1, 32])
    b_conv1 = bias_variable([32])
  10. x_image = tf.reshape(x, [-1,28,28,1])
  11. h_conv1 = tf.nn.relu(conv2d(x_image, W_conv1) + b_conv1)
    h_pool1 = max_pool_2x2(h_conv1)
  12. #d第二层卷积
    W_conv2 = weight_variable([5, 5, 32, 64])
    b_conv2 = bias_variable([64])
  13. h_conv2 = tf.nn.relu(conv2d(h_pool1, W_conv2) + b_conv2)
    h_pool2 = max_pool_2x2(h_conv2)
  14. #全连接层
    W_fc1 = weight_variable([7 * 7 * 64, 1024])
    b_fc1 = bias_variable([1024])
  15. h_pool2_flat = tf.reshape(h_pool2, [-1, 7*7*64])
    h_fc1 = tf.nn.relu(tf.matmul(h_pool2_flat, W_fc1) + b_fc1)
  16. keep_prob = tf.placeholder("float")
    h_fc1_drop = tf.nn.dropout(h_fc1, keep_prob)
  17. #输出层
    W_fc2 = weight_variable([1024, 10])
    b_fc2 = bias_variable([10])
  18. #训练和评估模型
    y_conv=tf.nn.softmax(tf.matmul(h_fc1_drop, W_fc2) + b_fc2)
    cross_entropy = -tf.reduce_sum(y_*tf.log(y_conv))
    train_step = tf.train.AdagradOptimizer(1e-4).minimize(cross_entropy)
    correct_prediction = tf.equal(tf.argmax(y_conv,1), tf.argmax(y_,1))
    accuracy = tf.reduce_mean(tf.cast(correct_prediction, "float"))
  19. ckpt_dir = "./ckpt_dir"
    if not os.path.exists(ckpt_dir):
       os.makedirs(ckpt_dir)
    #标志变量不参与到训练中
    global_step = tf.Variable(0, name='global_step', trainable=False)
    saver = tf.train.Saver()
  20. if int(sys.argv[1])>0:
       end=int(sys.argv[1])
    else:
       end=10000
  21. with tf.Session() as sess:
       ckpt = tf.train.get_checkpoint_state(ckpt_dir)
       if ckpt and ckpt.model_checkpoint_path:
           print(ckpt.model_checkpoint_path)
           saver.restore(sess, ckpt.model_checkpoint_path) # restore all variables
       else:
           tf.global_variables_initializer().run()
  22.    start = global_step.eval() # get last global_step
       print("Start from:", start)
  23.    for i in range(start, end):
         batch = mnist.train.next_batch(100)
         if i%10 == 0:
           train_accuracy = accuracy.eval(session=sess,feed_dict={
               x:batch[0], y_: batch[1], keep_prob: 1.0})
           print ("step %d, training accuracy %g"%(i, train_accuracy))
  24.      train_step.run(session=sess,feed_dict={x: batch[0], y_: batch[1], keep_prob: 0.5})
  25.      global_step.assign(i).eval()  #i更新global_step.
         saver.save(sess, ckpt_dir + "/model.ckpt", global_step=global_step)
  26.    print ("test accuracy %g"%accuracy.eval(session=sess,feed_dict={
           x: mnist.test.images, y_: mnist.test.labels, keep_prob: 1.0}))

训练16000次后,模型的准确率如图2:

模型测试

在第三步中完成了对模型的训练,本步骤中,笔者将对训练的模型进行效果测试,通过传入一张手写的数字图像,输出结果为模型对传入图像的识别结果,测试的图像可以从第二步中给出百度网盘地址下载。测试代码如下:(注:代码需要传入一个参数,即测试图像路径)

  1. # coding=utf-8
    import tensorflow as tf
    import os
    import numpy as np
    import sys
    from PIL import Image#pillow(PIL)
  2. x = tf.placeholder("float", shape=[None, 784])
    y_ = tf.placeholder("float", shape=[None, 10])
  3. W = tf.Variable(tf.zeros([784,10]))
    b = tf.Variable(tf.zeros([10]))
  4. def weight_variable(shape):
     initial = tf.truncated_normal(shape, stddev=0.1)
     return tf.Variable(initial)
  5. def bias_variable(shape):
     initial = tf.constant(0.1, shape=shape)
     return tf.Variable(initial)
  6. #权重初始化
    def conv2d(x, W):
     return tf.nn.conv2d(x, W, strides=[1, 1, 1, 1], padding='SAME')
  7. def max_pool_2x2(x):
     return tf.nn.max_pool(x, ksize=[1, 2, 2, 1],
                           strides=[1, 2, 2, 1], padding='SAME')
  8. #第一层卷积
    W_conv1 = weight_variable([5, 5, 1, 32])
    b_conv1 = bias_variable([32])
  9. x_image = tf.reshape(x, [-1,28,28,1])
  10. h_conv1 = tf.nn.relu(conv2d(x_image, W_conv1) + b_conv1)
    h_pool1 = max_pool_2x2(h_conv1)
  11. #d第二层卷积
    W_conv2 = weight_variable([5, 5, 32, 64])
    b_conv2 = bias_variable([64])
  12. h_conv2 = tf.nn.relu(conv2d(h_pool1, W_conv2) + b_conv2)
    h_pool2 = max_pool_2x2(h_conv2)
  13. #全连接层
    W_fc1 = weight_variable([7 * 7 * 64, 1024])
    b_fc1 = bias_variable([1024])
  14. h_pool2_flat = tf.reshape(h_pool2, [-1, 7*7*64])
    h_fc1 = tf.nn.relu(tf.matmul(h_pool2_flat, W_fc1) + b_fc1)
  15. keep_prob = tf.placeholder("float")
    h_fc1_drop = tf.nn.dropout(h_fc1, keep_prob)
  16. #输出层
    W_fc2 = weight_variable([1024, 10])
    b_fc2 = bias_variable([10])
  17. #训练和评估模型
    y_conv=tf.nn.softmax(tf.matmul(h_fc1_drop, W_fc2) + b_fc2)
  18. ckpt_dir = "./ckpt_dir"
  19. saver = tf.train.Saver()
    with tf.Session() as sess:
       ckpt = tf.train.get_checkpoint_state(ckpt_dir)
       if ckpt and ckpt.model_checkpoint_path:
           print(ckpt.model_checkpoint_path)
           saver.restore(sess, ckpt.model_checkpoint_path) # restore all variables
       else:
           raise FileNotFoundError("未找到模型")#raise 引发异常
  20.    # image_path="D:\\1.png"
       # image_path="/home/mnist/mnist03/test_data/"+sys.argv[1]+".png"
       image_path=sys.argv[1]
       print(image_path)
       img = Image.open(image_path).convert('L')#灰度图(L)
       img_shape = np.reshape(img, 784)
       real_x = np.array([1-img_shape])# 0-255 uint8   8位无符号整数,取值:[0, 255] 如果采用1-大数变成小数
       y = sess.run(y_conv, feed_dict={x: real_x,keep_prob: 1.0}) #y类似一个二维表,因为只有一张图片所以只有一行,y[0]包含10个值,
  21.    print('Predict digit', np.argmax(y[0]))#找出最大的值

效果展示

任意选择0至9的手写数字图片(图片像素大小28*28)传入到模型测试部分可以查看测试效果。本文笔者仅展示共4个手写数字的识别效果,大家可以测试更多(如需要测试图片请后台留联系方式)。

图3 测验数

图4 测验效果

由图3、4可以看出,4个手写字模型都准确的预测了出来,大家也可以尝试手写一张数字图像,并通过OpenCV处理转为28*28像素,进行识别。如果懒得动手写demo,请等待笔者的下一篇文章

参考文献:

1.http://yann.lecun.com/exdb/mnist/

2.http://wiki.jikexueyuan.com/project/tensorflow-zh/tutorials/mnist_tf.html

公众号历史精选文章:

深度学习(Deep Learning)资料大全(不断更新)

Deep Learning(深度学习)学习笔记之系列(一)

机器学习——逻辑回归

ALS音乐推荐(上)

Storm环境搭建(分布式集群)

SparkSQL—用之惜之

Spark系列1:开篇之组件云集

HDFS架构及原理

大数据家族成员概述

持续更新ing

用TensorFlow教你手写字识别的更多相关文章

  1. TensorFlow 入门之手写识别(MNIST) softmax算法

    TensorFlow 入门之手写识别(MNIST) softmax算法 MNIST flyu6 softmax回归 softmax回归算法 TensorFlow实现softmax softmax回归算 ...

  2. TensorFlow MNIST(手写识别 softmax)实例运行

    TensorFlow MNIST(手写识别 softmax)实例运行 首先要有编译环境,并且已经正确的编译安装,关于环境配置参考:http://www.cnblogs.com/dyufei/p/802 ...

  3. TensorFlow 入门之手写识别CNN 三

    TensorFlow 入门之手写识别CNN 三 MNIST 卷积神经网络 Fly 多层卷积网络 多层卷积网络的基本理论 构建一个多层卷积网络 权值初始化 卷积和池化 第一层卷积 第二层卷积 密集层连接 ...

  4. TensorFlow 入门之手写识别(MNIST) softmax算法 二

    TensorFlow 入门之手写识别(MNIST) softmax算法 二 MNIST Fly softmax回归 softmax回归算法 TensorFlow实现softmax softmax回归算 ...

  5. TensorFlow 入门之手写识别(MNIST) 数据处理 一

    TensorFlow 入门之手写识别(MNIST) 数据处理 一 MNIST Fly softmax回归 准备数据 解压 与 重构 手写识别入门 MNIST手写数据集 图片以及标签的数据格式处理 准备 ...

  6. knn算法手写字识别案例

    import pandas as pd import numpy as np import matplotlib.pyplot as plt import os from sklearn.neighb ...

  7. tensorflow卷积神经网络与手写字识别

    1.知识点 """ 基础知识: 1.神经网络(neural networks)的基本组成包括输入层.隐藏层.输出层.而卷积神经网络的特点在于隐藏层分为卷积层和池化层(po ...

  8. 基于tensorflow的MNIST手写识别

    这个例子,是学习tensorflow的人员通常会用到的,也是基本的学习曲线中的一环.我也是! 这个例子很简单,这里,就是简单的说下,不同的tensorflow版本,相关的接口函数,可能会有不一样哟.在 ...

  9. 使用tensorflow实现mnist手写识别(单层神经网络实现)

    import tensorflow as tf import tensorflow.examples.tutorials.mnist.input_data as input_data import n ...

随机推荐

  1. [NodeJs Windows编译学习]

    https://blog.csdn.net/gesturexiaoxin/article/details/80162944

  2. python3脚本打开摄像头

    openCamera 脚本地址:https://github.com/Mrlshadows/openCamera Mac OS 安装 OpenCV Python 环境为 python3 终端执行如下指 ...

  3. CSS文字的跑马灯特效

    上学时同学有个来电带跑马灯的手机,可把我羡慕坏了,可等我买的起手机时,跑马灯不流行了,甚伤萝卜心! 今天就用CSS做个文字的跑马灯特效,缅怀一下本萝卜逝去的青春! 道具:会敲代码的巧手.七窍玲珑心.会 ...

  4. Python-字典与json的转换

    #json是字符串,只不过长得像字典 import json user_info='''{"niuhy":1234,"shanbl":44566}''' #js ...

  5. C# 窗体打开拖动到窗体的文件

    private void Form3_DragEnter(object sender, DragEventArgs e) { if (e.Data.GetDataPresent(DataFormats ...

  6. Mesos源码分析(11): Mesos-Master接收到launchTasks消息

    根据Mesos源码分析(6): Mesos Master的初始化中的代码分析,当Mesos-Master接收到launchTask消息的时候,会调用Master::launchTasks函数.   v ...

  7. 深入理解Spring Redis的使用 (三)、使用RedisTemplate的操作类访问Redis

    上一篇说了RedisTemplate对注解事务的支持,以及提供的序列化器. 事务需要开启enableTransactionSupport,然后使用@transactional注解,里面直接通过回调的c ...

  8. 【DFS】n皇后问题

    回溯: 递归调用代表开启一个分支,如果希望这个分支返回后某些数据恢复到分支开启前的状态以便重新开始,就要使用到回溯技巧,全排列的交换法,数独,部分和,用到了回溯.下一个状态在开始之前需要利用到之前的状 ...

  9. [Swift]LeetCode633. 平方数之和 | Sum of Square Numbers

    Given a non-negative integer c, your task is to decide whether there're two integers a and b such th ...

  10. [Swift]LeetCode807. 保持城市天际线 | Max Increase to Keep City Skyline

    In a 2 dimensional array grid, each value grid[i][j]represents the height of a building located ther ...