本文將參考TensorFlow中文社區官方文檔使用mnist數據集訓練一個多層卷積神經網絡(LeNet5網絡),並利用所訓練的模型識別自己手寫數字。
訓練MNIST數據集,並保存訓練模型
# Python3
# 使用LeNet5的七層卷積神經網絡用於MNIST手寫數字識別
import tensorflow as tf
from tensorflow.examples.tutorials.mnist import input_data
mnist = input_data.read_data_sets("MNIST_data", one_hot=True)
# 為輸入圖像和目標輸出類別創建節點
x = tf.placeholder(tf.float32, shape=[None, 784]) # 訓練所需數據 占位符
y_ = tf.placeholder(tf.float32, shape=[None, 10]) # 訓練所需標簽數據 占位符
# *************** 構建多層卷積網絡 *************** #
# 權重、偏置、卷積及池化操作初始化,以避免在建立模型的時候反復做初始化操作
def weight_variable(shape):
initial = tf.truncated_normal(shape, stddev=0.1) # 取隨機值,符合均值為0,標准差stddev為0.1
return tf.Variable(initial)
def bias_variable(shape):
initial = tf.constant(0.1, shape=shape)
return tf.Variable(initial)
# x 的第一個參數為圖片的數量,第二、三個參數分別為圖片高度和寬度,第四個參數為圖片通道數。
# W 的前兩個參數為卷積核尺寸,第三個參數為圖像通道數,第四個參數為卷積核數量
# strides為卷積步長,其第一、四個參數必須為1,因為卷積層的步長只對矩陣的長和寬有效
# padding表示卷積的形式,即是否考慮邊界。"SAME"是考慮邊界,不足的時候用0去填充周圍,"VALID"則不考慮
def conv2d(x, W):
return tf.nn.conv2d(x, W, strides=[1, 1, 1, 1], padding='SAME')
# x 參數的格式同tf.nn.conv2d中的x,ksize為池化層過濾器的尺度,strides為過濾器步長
def max_pool_2x2(x):
return tf.nn.max_pool(x, ksize=[1, 2, 2, 1], strides=[1, 2, 2, 1], padding='SAME')
#把x更改為4維張量,第1維代表樣本數量,第2維和第3維代表圖像長寬, 第4維代表圖像通道數
x_image = tf.reshape(x, [-1,28,28,1]) # -1表示任意數量的樣本數,大小為28x28,深度為1的張量
# 第一層:卷積
W_conv1 = weight_variable([5, 5, 1, 32]) # 卷積在每個5x5的patch中算出32個特征。
b_conv1 = bias_variable([32])
h_conv1 = tf.nn.relu(conv2d(x_image, W_conv1) + b_conv1)
# 第二層:池化
h_pool1 = max_pool_2x2(h_conv1)
# 第三層:卷積
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)
# 在輸出層之前加入dropout以減少過擬合
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.AdamOptimizer(1e-4).minimize(cross_entropy)
# 檢測我們的預測是否真實標簽匹配(索引位置一樣表示匹配)
# tf.argmax(y_conv,dimension), 返回最大數值的下標 通常和tf.equal()一起使用,計算模型准確度
# dimension=0 按列找 dimension=1 按行找
correct_prediction = tf.equal(tf.argmax(y_conv,1), tf.argmax(y_,1))
# 統計測試准確率, 將correct_prediction的布爾值轉換為浮點數來代表對、錯,並取平均值。
accuracy = tf.reduce_mean(tf.cast(correct_prediction, "float"))
saver = tf.train.Saver() # 定義saver
# *************** 開始訓練模型 *************** #
with tf.Session() as sess:
sess.run(tf.global_variables_initializer())
for i in range(1000):
batch = mnist.train.next_batch(50)
if i%100 == 0:
# 評估模型准確度,此階段不使用Dropout
train_accuracy = accuracy.eval(feed_dict={x:batch[0], y_: batch[1], keep_prob: 1.0})
print("step %d, training accuracy %g"%(i, train_accuracy))
# 訓練模型,此階段使用50%的Dropout
train_step.run(feed_dict={x: batch[0], y_: batch[1], keep_prob: 0.5})
saver.save(sess, './save/model.ckpt') #模型儲存位置
print("test accuracy %g"%accuracy.eval(feed_dict={x: mnist.test.images [0:2000], y_: mnist.test.labels [0:2000], keep_prob: 1.0}))
手寫數字圖像預處理
然后自己手寫數字

利用Python和OpenCV進行圖像預處理
需要安裝Python的OpenCV接口(安裝命令:pip install opencv-python)
MNIST要求數據為28*28像素,單通道,且需要二值化。
import cv2
global img
global point1, point2
def on_mouse(event, x, y, flags, param):
global img, point1, point2
img2 = img.copy()
if event == cv2.EVENT_LBUTTONDOWN: #左鍵點擊
point1 = (x,y)
cv2.circle(img2, point1, 10, (0,255,0), 5)
cv2.imshow('image', img2)
elif event == cv2.EVENT_MOUSEMOVE and (flags & cv2.EVENT_FLAG_LBUTTON): #按住左鍵拖曳
cv2.rectangle(img2, point1, (x,y), (255,0,0), 5) # 圖像,矩形頂點,相對頂點,顏色,粗細
cv2.imshow('image', img2)
elif event == cv2.EVENT_LBUTTONUP: #左鍵釋放
point2 = (x,y)
cv2.rectangle(img2, point1, point2, (0,0,255), 5)
cv2.imshow('image', img2)
min_x = min(point1[0], point2[0])
min_y = min(point1[1], point2[1])
width = abs(point1[0] - point2[0])
height = abs(point1[1] -point2[1])
cut_img = img[min_y:min_y+height, min_x:min_x+width]
resize_img = cv2.resize(cut_img, (28,28)) # 調整圖像尺寸為28*28
ret, thresh_img = cv2.threshold(resize_img,127,255,cv2.THRESH_BINARY) # 二值化
cv2.imshow('result', thresh_img)
cv2.imwrite('./images/text.png', thresh_img) # 預處理后圖像保存位置
def main():
global img
img = cv2.imread('./images/src.jpg') # 手寫數字圖像所在位置
img = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY) # 轉換圖像為單通道(灰度圖)
cv2.namedWindow('image')
cv2.setMouseCallback('image', on_mouse) # 調用回調函數
cv2.imshow('image', img)
cv2.waitKey(0)
if __name__ == '__main__':
main()
運行上方代碼,利用鼠標框選自己手寫數字區域,完成圖像預處理,可得到如下圖像

手寫數字識別
完成圖像預處理后,即可將圖片輸入到網絡中進行識別
from PIL import Image
import tensorflow as tf
import numpy as np
im = Image.open('./images/text.png')
data = list(im.getdata())
result = [(255-x)*1.0/255.0 for x in data]
print(result)
# 為輸入圖像和目標輸出類別創建節點
x = tf.placeholder("float", shape=[None, 784]) # 訓練所需數據 占位符
# *************** 構建多層卷積網絡 *************** #
def weight_variable(shape):
initial = tf.truncated_normal(shape, stddev=0.1) # 取隨機值,符合均值為0,標准差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')
x_image = tf.reshape(x, [-1,28,28,1]) # -1表示任意數量的樣本數,大小為28x28,深度為1的張量
W_conv1 = weight_variable([5, 5, 1, 32]) # 卷積在每個5x5的patch中算出32個特征。
b_conv1 = bias_variable([32])
h_conv1 = tf.nn.relu(conv2d(x_image, W_conv1) + b_conv1)
h_pool1 = max_pool_2x2(h_conv1)
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)
# 在輸出層之前加入dropout以減少過擬合
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])
# 輸出層
# tf.nn.softmax()將神經網絡的輸層變成一個概率分布
y_conv=tf.nn.softmax(tf.matmul(h_fc1_drop, W_fc2) + b_fc2)
saver = tf.train.Saver() # 定義saver
# *************** 開始識別 *************** #
with tf.Session() as sess:
sess.run(tf.global_variables_initializer())
saver.restore(sess, "./save/model.ckpt")#這里使用了之前保存的模型參數
prediction = tf.argmax(y_conv,1)
predint = prediction.eval(feed_dict={x: [result],keep_prob: 1.0}, session=sess)
print("recognize result: %d" %predint[0])
運行上述程序,即可得到識別結果,如下圖所示:

可以看到識別的結果為3, 大功告成!
