用TensorFlow教你手写字识别

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 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:
在这里插入图片描述

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 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的手写数字图片(图片像素大小2828)传入到模型测试部分可以查看测试效果。本文笔者仅展示共4个手写数字的识别效果,大家可以测试更多(如需要测试图片请后台留联系方式)。
在这里插入图片描述
图3 测验数图3 测验数图3 测验数图3 测验数
在这里插入图片描述
由图3、4可以看出,4个手写字模型都准确的预测了出来,大家也可以尝试手写一张数字图像,并通过OpenCV处理转为28
28像素,进行识别。如果懒得动手写demo,请等待笔者的下一篇文章

评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值