用TensorFlow教你手寫字識別

博主原文連接:用TensorFlow教你作手寫字識別(準確率94.09%)html

如需轉載,請備註出處及連接,謝謝。python

 

2012 年,Alex Krizhevsky, Geoff Hinton, and Ilya Sutskever 贏得 ImageNet 挑戰賽冠軍,基於CNN的圖像識別開始受到廣泛關注,CNN 成爲了圖像分類的黃金標準,自那之後,科學界掀開了基於深度神經網絡對圖像識別的大探索,現現在,深度學習對圖像的識別能力已經超出了人眼的辨別能力。本公衆號的圖像識別系列將按部就班,層層深刻的帶領讀者去學習圖像識別,本篇中筆者將帶領讀者一塊完成基於CNN的手寫數字圖像識別。linux

 

工具要求git

工具及環境要求以下,若是你們在安裝TensorFlow過程遇到問題,能夠諮詢筆者一塊兒探討。網絡

  • Python 2.7.14session

  • TensorFlow 1.5架構

  • pip 10.0.1機器學習

  • linux環境分佈式

 

MNIST數據集ide

基於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 測驗效果

 

由圖三、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

 

 

相關文章
相關標籤/搜索