1、MNIST数据集

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

图1 MNIST数据集

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

2、模型训练

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

# -*- coding: utf-8 -*-
import tensorflow as tf
import tensorflow.examples.tutorials.mnist.input_data as input_data
import osmnist = input_data.read_data_sets('MNIST_data', one_hot=True)x = tf.placeholder("float", shape=[None, 784])
y_ = tf.placeholder("float", shape=[None, 10])W = tf.Variable(tf.zeros([784,10]))
b = tf.Variable(tf.zeros([10]))def weight_variable(shape):initial = tf.truncated_normal(shape, stddev=0.1)return tf.Variable(initial)def bias_variable(shape):initial = tf.constant(0.1, shape=shape)return tf.Variable(initial)#权重初始化
def conv2d(x, W):return tf.nn.conv2d(x, W, strides=[1, 1, 1, 1], padding='SAME')def max_pool_2x2(x):return tf.nn.max_pool(x, ksize=[1, 2, 2, 1],strides=[1, 2, 2, 1], padding='SAME')#第一层卷积
W_conv1 = weight_variable([5, 5, 1, 32])
b_conv1 = bias_variable([32])x_image = tf.reshape(x, [-1,28,28,1])h_conv1 = tf.nn.relu(conv2d(x_image, W_conv1) + b_conv1)
h_pool1 = max_pool_2x2(h_conv1)#d第二层卷积
W_conv2 = weight_variable([5, 5, 32, 64])
b_conv2 = bias_variable([64])h_conv2 = tf.nn.relu(conv2d(h_pool1, W_conv2) + b_conv2)
h_pool2 = max_pool_2x2(h_conv2)#全连接层
W_fc1 = weight_variable([7 * 7 * 64, 1024])
b_fc1 = bias_variable([1024])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)keep_prob = tf.placeholder("float")
h_fc1_drop = tf.nn.dropout(h_fc1, keep_prob)#输出层
W_fc2 = weight_variable([1024, 10])
b_fc2 = bias_variable([10])#训练和评估模型
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"))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()if int(sys.argv[1])>0:end=int(sys.argv[1])
else:end=10000with 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 variableselse:tf.global_variables_initializer().run()start = global_step.eval() # get last global_stepprint("Start from:", start)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))train_step.run(session=sess,feed_dict={x: batch[0], y_: batch[1], keep_prob: 0.5})global_step.assign(i).eval()  #i更新global_step.saver.save(sess, ckpt_dir + "/model.ckpt", global_step=global_step)print ("test accuracy %g"%accuracy.eval(session=sess,feed_dict={x: mnist.test.images, y_: mnist.test.labels, keep_prob: 1.0}))

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

3、模型测试

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

# coding=utf-8
import tensorflow as tf
import os
import numpy as np
import sys
from PIL import Image#pillow(PIL)x = tf.placeholder("float", shape=[None, 784])
y_ = tf.placeholder("float", shape=[None, 10])W = tf.Variable(tf.zeros([784,10]))
b = tf.Variable(tf.zeros([10]))def weight_variable(shape):initial = tf.truncated_normal(shape, stddev=0.1)return tf.Variable(initial)def bias_variable(shape):initial = tf.constant(0.1, shape=shape)return tf.Variable(initial)#权重初始化
def conv2d(x, W):return tf.nn.conv2d(x, W, strides=[1, 1, 1, 1], padding='SAME')def max_pool_2x2(x):return tf.nn.max_pool(x, ksize=[1, 2, 2, 1],strides=[1, 2, 2, 1], padding='SAME')#第一层卷积
W_conv1 = weight_variable([5, 5, 1, 32])
b_conv1 = bias_variable([32])x_image = tf.reshape(x, [-1,28,28,1])h_conv1 = tf.nn.relu(conv2d(x_image, W_conv1) + b_conv1)
h_pool1 = max_pool_2x2(h_conv1)#d第二层卷积
W_conv2 = weight_variable([5, 5, 32, 64])
b_conv2 = bias_variable([64])h_conv2 = tf.nn.relu(conv2d(h_pool1, W_conv2) + b_conv2)
h_pool2 = max_pool_2x2(h_conv2)#全连接层
W_fc1 = weight_variable([7 * 7 * 64, 1024])
b_fc1 = bias_variable([1024])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)keep_prob = tf.placeholder("float")
h_fc1_drop = tf.nn.dropout(h_fc1, keep_prob)#输出层
W_fc2 = weight_variable([1024, 10])
b_fc2 = bias_variable([10])#训练和评估模型
y_conv=tf.nn.softmax(tf.matmul(h_fc1_drop, W_fc2) + b_fc2)ckpt_dir = "./ckpt_dir"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 variableselse:raise FileNotFoundError("未找到模型")#raise 引发异常# 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个值,print('Predict digit', np.argmax(y[0]))#找出最大的值

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

图3 测验数图3 测验数图3 测验数图3 测验数

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

用TensorFlow教你手写字识别相关推荐

  1. 基于tensorflow的MNIST手写字识别

    一.卷积神经网络模型知识要点卷积卷积 1.卷积 2.池化 3.全连接 4.梯度下降法 5.softmax 本次就是用最简单的方法给大家讲解这些概念,因为具体的各种论文网上都有,连推导都有,所以本文主要 ...

  2. 基于tensorflow的MNIST手写字识别(一)--白话卷积神经网络模型

    一.卷积神经网络模型知识要点卷积卷积 1.卷积 2.池化 3.全连接 4.梯度下降法 5.softmax 本次就是用最简单的方法给大家讲解这些概念,因为具体的各种论文网上都有,连推导都有,所以本文主要 ...

  3. TensorFlow基于minist数据集实现手写字识别实战的三个模型

    手写字识别 model1:输入层→全连接→输出层softmax model2:输入层→全连接→隐含层→全连接→输出层softmax model3:输入层→卷积层1→卷积层2→全连接→dropout层→ ...

  4. 在Windows上调试TensorFlow 2.0 中文手写字识别(汉字OCR)

    在Windows上调试TensorFlow 2.0 中文手写字识别(汉字OCR) 一.环境的搭建 Windows+1080Ti+Cuda10.1 Tsorflow2.0.0 Numpy1.16.4 注 ...

  5. python手写汉字识别_TensorFlow 2.0实践之中文手写字识别

    问题导读: 1.相比于简单minist识别,汉字识别具有哪些难点? 2.如何快速的构建一个OCR网络模型? 3.读取的时候有哪些点需要注意? 4.如何让模型更简单的收敛? 还在玩minist?fash ...

  6. .net 数字转汉字_TensorFlow 2.0 中文手写字识别(汉字OCR)

    TensorFlow 2.0 中文手写字识别(汉字OCR) 在开始之前,必须要说明的是,本教程完全基于TensorFlow2.0 接口编写,请误与其他古老的教程混为一谈,本教程除了手把手教大家完成这个 ...

  7. 最终章 | TensorFlow战Kaggle“手写识别达成99%准确率

    刘颖,某互联网创业公司COO,技术出身,做产品里最懂运营的. 这是一个TensorFlow的系列文章,本文是第三篇,在这个系列中,你讲了解到机器学习的一些基本概念.TensorFlow的使用,并能实际 ...

  8. 利用卷积神经网络实现手写字识别

    本文我们介绍一下卷积神经网络,然后基于pytorch实现一个卷积神经网络,并实现手写字识别 卷积神经网络介绍 传统神经网络处理图片问题的不足 让我们先复习一下神经网络的工作流程: 搭建一个神经网络 将 ...

  9. 利用神经网络实现手写字识别

    神经网络介绍 神经网络即多层感知机 如果不知道感知机的可以看博主之前的文章感知机及Python实现 神经网络实现及手写字识别 关于数据集: 从http://yann.lecun.com/exdb/mn ...

最新文章

  1. 自动类型转换和强制类型转换
  2. NC:你觉得你吃的是草,其实你还是吃的土(遗传发育所朱峰)
  3. Discuz! X3.2新增管理员无法登录后台的解决办法
  4. 农民丰收节交易英德海奇组委会议-陈业海:功能农业大健康
  5. Wi-Fi模块的设置方法汇总
  6. AUTOSAR从入门到精通100讲(三十六)-AUTOSAR 通信服务两步走-CanSM概念-配置及代码分析
  7. android 控制word,Android使用POI进行Word操作(一)
  8. 漫步线性代数五——三角分解和行交换
  9. vue中标签自定义属性的使用
  10. 用Python破解数学教育
  11. 苹果11如何设置9宫格_iphone九宫格如何设置 iphone九宫格设置方法【详解】
  12. 费尔德曼的百吉饼实验:人类的诚实程度其实超出你的想象!
  13. elt php,ELT(数据仓库技术) 学习
  14. STM32 学习总结2 ----利用中断来控制按键点灯、捕获功能练习
  15. 《中国人史纲》读书笔记:第二章 神话时代 第三章 传说时代
  16. 根据图片名批量创建文件夹
  17. (34.1)【登录越权/爆破专题】原理、字典资源、工具、利用过程……
  18. UINO优锘:数字孪生助力运维工程场景化可视化管理
  19. 锋迷商城项目介绍(一)
  20. 一次服务器上g1回收器发生fullgc的粗浅理解与记录

热门文章

  1. 模拟计算MS软件常见问题及解答(二)
  2. 前端加油鸭!【FCC】JavaScript基础(1)
  3. 基于注意力机制的seq2seq模型
  4. UIControl 详细解释
  5. 罗伯特.巴尼台球教程
  6. $emit自定义子组件和父组件通信
  7. python并发处理同一个文件_python并发编程(并发与并行,同步和异步,阻塞与非阻塞)...
  8. [Linux Audio Driver] 高通TDM总线配置
  9. 【紫光同创国产FPGA教程】【第二章】LED流水灯实验及仿真
  10. 如何查看进程工作路径