博主原文鏈接:用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