基于MNIST數(shù)據(jù)集實(shí)現(xiàn)手寫數(shù)字識(shí)別

介紹

在TensorFlow的官方入門課程中叮趴,多次用到mnist數(shù)據(jù)集。mnist數(shù)據(jù)集是一個(gè)數(shù)字手寫體圖片庫权烧,但它的存儲(chǔ)格式并非常見的圖片格式眯亦,所有的圖片都集中保存在四個(gè)擴(kuò)展名為idx*-ubyte.gz的二進(jìn)制文件。

數(shù)據(jù)集

可以直接從官網(wǎng)進(jìn)行下載
http://yann.lecun.com/exdb/mnist/

數(shù)據(jù)集

如果我們想要知道大名鼎鼎的mnist手寫體數(shù)字都長什么樣子般码,就需要從mnist數(shù)據(jù)集中導(dǎo)出手寫體數(shù)字圖片妻率。了解這些手寫體的總體形狀,也有助于加深我們對TensorFlow入門課程的理解板祝。

訓(xùn)練數(shù)據(jù)集

當(dāng)我們下載了數(shù)據(jù)集后宫静,需要對數(shù)據(jù)集進(jìn)行訓(xùn)練。并保存訓(xùn)練的模型

#!/usr/bin/python3.5
# -*- coding: utf-8 -*-
from tensorflow.examples.tutorials.mnist import input_data

import tensorflow as tf

mnist = input_data.read_data_sets('MNIST_data', one_hot=True)

x = tf.placeholder(tf.float32, [None, 784])

y_ = tf.placeholder(tf.float32, [None, 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)

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.AdamOptimizer(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"))

saver = tf.train.Saver()

with tf.Session() as sess:
    sess.run(tf.global_variables_initializer())
    for i in range(20000):
        batch = mnist.train.next_batch(50)
        if i % 100 == 0:
            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))
        train_step.run(feed_dict={x: batch[0], y_: batch[1], keep_prob: 0.5})
    saver.save(sess, 'WModel/model.ckpt')

    print('test accuracy %g' % accuracy.eval(feed_dict={
        x: mnist.test.images, y_: mnist.test.labels, keep_prob: 1.0}))

對應(yīng)的模型文件如圖所示


模型

用畫圖手寫數(shù)字

通過電腦自帶畫圖工具券时,手寫一個(gè)數(shù)字孤里,像素為28,如圖所示

在這里插入圖片描述

識(shí)別手寫數(shù)字

把上面生成的圖片保存為bmp或png
然后通過程序調(diào)用橘洞,在使用之前需要先加載前面保存的模型

#!/usr/bin/python3.5
# -*- coding: utf-8 -*-
from PIL import Image, ImageFilter
import tensorflow as tf
import matplotlib.pyplot as plt
import time

def imageprepare():
    """
    This function returns the pixel values.
    The imput is a png file location.
    """
    file_name='result/4.bmp'#導(dǎo)入自己的圖片地址
    #in terminal 'mogrify -format png *.jpg' convert jpg to png
    im = Image.open(file_name)
    # plt.imshow(im)
    # plt.show()
    im = im.convert('L')

    im.save("sample.png")
    
    
    tv = list(im.getdata()) #get pixel values

    #normalize pixels to 0 and 1. 0 is pure white, 1 is pure black.
    tva = [ (255-x)*1.0/255.0 for x in tv] 
    #print(tva)
    return tva



    """
    This function returns the predicted integer.
    The imput is the pixel values from the imageprepare() function.
    """

    # Define the model (same as when creating the model file)

result=imageprepare()


x = tf.placeholder(tf.float32, [None, 784])

y_ = tf.placeholder(tf.float32, [None, 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)

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.AdamOptimizer(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"))

saver = tf.train.Saver()
with tf.Session() as sess:
    sess.run(tf.global_variables_initializer())
    saver.restore(sess, "./WModel/model.ckpt")#這里使用了之前保存的模型參數(shù)
    print ("Model restored.")

    prediction=tf.argmax(y_conv,1)
    predint=prediction.eval(feed_dict={x: [result],keep_prob: 1.0}, session=sess)
    print(h_conv2)

    print('識(shí)別結(jié)果:')
    print(predint[0])

識(shí)別結(jié)果如圖所示:


運(yùn)行結(jié)果
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請聯(lián)系作者
  • 序言:七十年代末捌袜,一起剝皮案震驚了整個(gè)濱河市,隨后出現(xiàn)的幾起案子炸枣,更是在濱河造成了極大的恐慌虏等,老刑警劉巖,帶你破解...
    沈念sama閱讀 219,427評(píng)論 6 508
  • 序言:濱河連續(xù)發(fā)生了三起死亡事件抛虏,死亡現(xiàn)場離奇詭異博其,居然都是意外死亡,警方通過查閱死者的電腦和手機(jī)迂猴,發(fā)現(xiàn)死者居然都...
    沈念sama閱讀 93,551評(píng)論 3 395
  • 文/潘曉璐 我一進(jìn)店門慕淡,熙熙樓的掌柜王于貴愁眉苦臉地迎上來,“玉大人沸毁,你說我怎么就攤上這事峰髓。” “怎么了息尺?”我有些...
    開封第一講書人閱讀 165,747評(píng)論 0 356
  • 文/不壞的土叔 我叫張陵携兵,是天一觀的道長。 經(jīng)常有香客問我搂誉,道長徐紧,這世上最難降的妖魔是什么? 我笑而不...
    開封第一講書人閱讀 58,939評(píng)論 1 295
  • 正文 為了忘掉前任,我火速辦了婚禮并级,結(jié)果婚禮上拂檩,老公的妹妹穿的比我還像新娘。我一直安慰自己嘲碧,他們只是感情好稻励,可當(dāng)我...
    茶點(diǎn)故事閱讀 67,955評(píng)論 6 392
  • 文/花漫 我一把揭開白布。 她就那樣靜靜地躺著愈涩,像睡著了一般望抽。 火紅的嫁衣襯著肌膚如雪。 梳的紋絲不亂的頭發(fā)上履婉,一...
    開封第一講書人閱讀 51,737評(píng)論 1 305
  • 那天煤篙,我揣著相機(jī)與錄音,去河邊找鬼谐鼎。 笑死舰蟆,一個(gè)胖子當(dāng)著我的面吹牛,可吹牛的內(nèi)容都是我干的狸棍。 我是一名探鬼主播身害,決...
    沈念sama閱讀 40,448評(píng)論 3 420
  • 文/蒼蘭香墨 我猛地睜開眼,長吁一口氣:“原來是場噩夢啊……” “哼草戈!你這毒婦竟也來了塌鸯?” 一聲冷哼從身側(cè)響起,我...
    開封第一講書人閱讀 39,352評(píng)論 0 276
  • 序言:老撾萬榮一對情侶失蹤唐片,失蹤者是張志新(化名)和其女友劉穎丙猬,沒想到半個(gè)月后,有當(dāng)?shù)厝嗽跇淞掷锇l(fā)現(xiàn)了一具尸體费韭,經(jīng)...
    沈念sama閱讀 45,834評(píng)論 1 317
  • 正文 獨(dú)居荒郊野嶺守林人離奇死亡茧球,尸身上長有42處帶血的膿包…… 初始之章·張勛 以下內(nèi)容為張勛視角 年9月15日...
    茶點(diǎn)故事閱讀 37,992評(píng)論 3 338
  • 正文 我和宋清朗相戀三年,在試婚紗的時(shí)候發(fā)現(xiàn)自己被綠了星持。 大學(xué)時(shí)的朋友給我發(fā)了我未婚夫和他白月光在一起吃飯的照片抢埋。...
    茶點(diǎn)故事閱讀 40,133評(píng)論 1 351
  • 序言:一個(gè)原本活蹦亂跳的男人離奇死亡,死狀恐怖督暂,靈堂內(nèi)的尸體忽然破棺而出揪垄,到底是詐尸還是另有隱情,我是刑警寧澤逻翁,帶...
    沈念sama閱讀 35,815評(píng)論 5 346
  • 正文 年R本政府宣布饥努,位于F島的核電站,受9級(jí)特大地震影響八回,放射性物質(zhì)發(fā)生泄漏酷愧。R本人自食惡果不足惜驾诈,卻給世界環(huán)境...
    茶點(diǎn)故事閱讀 41,477評(píng)論 3 331
  • 文/蒙蒙 一、第九天 我趴在偏房一處隱蔽的房頂上張望伟墙。 院中可真熱鬧翘鸭,春花似錦、人聲如沸戳葵。這莊子的主人今日做“春日...
    開封第一講書人閱讀 32,022評(píng)論 0 22
  • 文/蒼蘭香墨 我抬頭看了看天上的太陽拱烁。三九已至,卻和暖如春噩翠,著一層夾襖步出監(jiān)牢的瞬間戏自,已是汗流浹背。 一陣腳步聲響...
    開封第一講書人閱讀 33,147評(píng)論 1 272
  • 我被黑心中介騙來泰國打工伤锚, 沒想到剛下飛機(jī)就差點(diǎn)兒被人妖公主榨干…… 1. 我叫王不留擅笔,地道東北人。 一個(gè)月前我還...
    沈念sama閱讀 48,398評(píng)論 3 373
  • 正文 我出身青樓屯援,卻偏偏與公主長得像猛们,于是被迫代替她去往敵國和親。 傳聞我的和親對象是個(gè)殘疾皇子狞洋,可洞房花燭夜當(dāng)晚...
    茶點(diǎn)故事閱讀 45,077評(píng)論 2 355

推薦閱讀更多精彩內(nèi)容