用TensorFlow教你手写字识别
博主原文链接:用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次的时候测试了一下识别效果,表现已经很不错了,如果大家想进一步提高准确率建议进一步提高训练次数或者丰富数据集等。不多说了,直接上代码:
# -*- coding: utf-8 -*-
import tensorflow as tf
import tensorflow.examples.tutorials.mnist.input_data as input_data
import os
mnist = 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=10000
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()
start = global_step.eval() # get last global_step
print("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:
模型测试
在第三步中完成了对模型的训练,本步骤中,笔者将对训练的模型进行效果测试,通过传入一张手写的数字图像,输出结果为模型对传入图像的识别结果,测试的图像可以从第二步中给出百度网盘地址下载。测试代码如下:(注:代码需要传入一个参数,即测试图像路径)
# 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 variables
else:
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的手写数字图片(图片像素大小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
公众号历史精选文章:
持续更新ing
用TensorFlow教你手写字识别的更多相关文章
- TensorFlow 入门之手写识别(MNIST) softmax算法
TensorFlow 入门之手写识别(MNIST) softmax算法 MNIST flyu6 softmax回归 softmax回归算法 TensorFlow实现softmax softmax回归算 ...
- TensorFlow MNIST(手写识别 softmax)实例运行
TensorFlow MNIST(手写识别 softmax)实例运行 首先要有编译环境,并且已经正确的编译安装,关于环境配置参考:http://www.cnblogs.com/dyufei/p/802 ...
- TensorFlow 入门之手写识别CNN 三
TensorFlow 入门之手写识别CNN 三 MNIST 卷积神经网络 Fly 多层卷积网络 多层卷积网络的基本理论 构建一个多层卷积网络 权值初始化 卷积和池化 第一层卷积 第二层卷积 密集层连接 ...
- TensorFlow 入门之手写识别(MNIST) softmax算法 二
TensorFlow 入门之手写识别(MNIST) softmax算法 二 MNIST Fly softmax回归 softmax回归算法 TensorFlow实现softmax softmax回归算 ...
- TensorFlow 入门之手写识别(MNIST) 数据处理 一
TensorFlow 入门之手写识别(MNIST) 数据处理 一 MNIST Fly softmax回归 准备数据 解压 与 重构 手写识别入门 MNIST手写数据集 图片以及标签的数据格式处理 准备 ...
- knn算法手写字识别案例
import pandas as pd import numpy as np import matplotlib.pyplot as plt import os from sklearn.neighb ...
- tensorflow卷积神经网络与手写字识别
1.知识点 """ 基础知识: 1.神经网络(neural networks)的基本组成包括输入层.隐藏层.输出层.而卷积神经网络的特点在于隐藏层分为卷积层和池化层(po ...
- 基于tensorflow的MNIST手写识别
这个例子,是学习tensorflow的人员通常会用到的,也是基本的学习曲线中的一环.我也是! 这个例子很简单,这里,就是简单的说下,不同的tensorflow版本,相关的接口函数,可能会有不一样哟.在 ...
- 使用tensorflow实现mnist手写识别(单层神经网络实现)
import tensorflow as tf import tensorflow.examples.tutorials.mnist.input_data as input_data import n ...
随机推荐
- python学习:输入设置
输入设置 输入用户名和密码 代码: _user = "alex"_password = "abc123" username = input("User ...
- TP框架下载功能
namespace Home\Controller; use Think\Controller; use Org\Net\Http; class IndexController extends Con ...
- django介绍及路由系统
第一:Python的web框架介绍 Python的WEB框架有Django.Tornado.Flask 等多种,Django相较与其他WEB框架其优势为:大而全,框架本身集成了ORM.模型绑定.模板引 ...
- 航班座位_hihocoder
题目2 : 航班座位 时间限制:10000ms 单点时限:1000ms 内存限制:256MB 描述 小Hi在给一个家庭旅游团订某次航班的机票.该航班的飞机一共有N排座位,每排座位有10个座位,从左到右 ...
- 4.再来看看逆向——OD的简介
目录 1.前言 2.一些设置和配置 3.开始了解OD 代码窗口 数据窗口 小端序问题 前言 前3节主要写了恶意代码用到的手段,接下来先写一下关于逆向调试的一些内容.毕竟逆向比较难理解一点. 一些配置和 ...
- vue组件里定时器销毁问题
我在a页面写一个定时,让他每秒钟打印一个1,然后跳转到b页面,此时可以看到,定时器依然在执行.这样是非常消耗性能的.如下图所示: 解决方法1: 首先我在data函数里面进行定义定时器名称: data( ...
- Data Center手册(4):设计
基础架构 拓扑图 Switching Path L3 routing at aggregation layer L2 switching at access layer L3 switch融合了三种功 ...
- [Swift]LeetCode650. 只有两个键的键盘 | 2 Keys Keyboard
Initially on a notepad only one character 'A' is present. You can perform two operations on this not ...
- [Swift]LeetCode802. 找到最终的安全状态 | Find Eventual Safe States
In a directed graph, we start at some node and every turn, walk along a directed edge of the graph. ...
- Jmeter-常用线程组设置及场景运行时间计算
Jmeter中通过线程组来模拟大用户并发场景,今天主要介绍三个常用的线程组,帮助我们设计更加完善的测试场景,另外介绍下场景执行时间如何计算. 一.Thread Group 取样器错误后要执行的动作 ...