keras實現(xiàn)手寫數字識別(數據集:MNIST)

準備工作

  • keras
  • tensorflow
  • numpy
  • PIL

下載MNIST數據集

from keras.dataset import mnist

mnist.load_data(path)

path是保存的路徑

模型結構

model1.png

這個模型用了兩個Convolution2D層抹估,兩個MaxPooling2D層,一個Flatten層,兩個全連接Dense層控妻,使用的激活函數是relu呀闻,優(yōu)化器是adam

訓練代碼

from keras.model import Sequential
from keras.layers import Convolution2D, Dense, Flatten, Activation, MaxPooling2D
from keras.utils import to_catagorical
from keras.optimizers import Adam
import numpy as np

(x_train, y_train), (x_test, y_test) = mnist.load_data()
x_train = x_train.reshape(60000, 28, 28, 1)
x_test = x_test.reshape(10000, 28, 28, 1)
y_test = to_categorical(y_test, 10)
y_train = to_categorical(y_train, 10)

# design model
model = Sequential()
model.add(Convolution2D(25, (5, 5), input_shape=(28, 28, 1)))
model.add(MaxPooling2D(2, 2))
model.add(Activation('relu'))
model.add(Convolution2D(50, (5, 5)))
model.add(MaxPooling2D(2, 2))
model.add(Activation('relu'))
model.add(Flatten())

model.add(Dense(50))
model.add(Activation('relu'))
model.add(Dense(10))
model.add(Activation('softmax'))
adam = Adam(lr=0.001)
# compile model
model.compile(optimizer=adam,loss='categorical_crossentropy',metrics=['accuracy'])
# training model
model.fit(x_train, y_train, batch_size=100, epochs=5)
# test model
print model.evaluate(x_test, y_test, batch_size=100)
# save model
model.save('/Users/zhang/Desktop/my_model2.h5')
訓練效果
Using TensorFlow backend.
Epoch 1/5
2017-09-12 14:49:32.779373: W tensorflow/core/platform/cpu_feature_guard.cc:45] The TensorFlow library wasn't compiled to use SSE4.1 instructions, but these are available on your machine and could speed up CPU computations.
2017-09-12 14:49:32.779389: W tensorflow/core/platform/cpu_feature_guard.cc:45] The TensorFlow library wasn't compiled to use SSE4.2 instructions, but these are available on your machine and could speed up CPU computations.
2017-09-12 14:49:32.779393: W tensorflow/core/platform/cpu_feature_guard.cc:45] The TensorFlow library wasn't compiled to use AVX instructions, but these are available on your machine and could speed up CPU computations.
2017-09-12 14:49:32.779398: W tensorflow/core/platform/cpu_feature_guard.cc:45] The TensorFlow library wasn't compiled to use AVX2 instructions, but these are available on your machine and could speed up CPU computations.
2017-09-12 14:49:32.779401: W tensorflow/core/platform/cpu_feature_guard.cc:45] The TensorFlow library wasn't compiled to use FMA instructions, but these are available on your machine and could speed up CPU computations.
60000/60000 [==============================] - 33s - loss: 2.5862 - acc: 0.8057    
Epoch 2/5
60000/60000 [==============================] - 32s - loss: 0.0603 - acc: 0.9820    
Epoch 3/5
60000/60000 [==============================] - 32s - loss: 0.0409 - acc: 0.9873    
Epoch 4/5
60000/60000 [==============================] - 32s - loss: 0.0338 - acc: 0.9895    
Epoch 5/5
60000/60000 [==============================] - 33s - loss: 0.0259 - acc: 0.9922    
 9900/10000 [============================>.] - ETA: 0s[0.054905540546023986, 0.98440000832080843]
  • 可以看到在測試集上識別準確率達到了98.44%厨相。
  • 其實在訓練過程中存在運氣問題炼七,對于batch_size=100來說傀履,如果從一開始沒有跑出最優(yōu)值虱朵,可能就進入了死胡同,導致訓練的準確率一直只有9%钓账。
  • 經過一輪訓練就能達到80%的準確率碴犬,這樣的訓練效果很有可能導致過擬合,雖然在測試集上有98%的準確率梆暮。

測試

我用ps畫出了幾個手寫數字的圖片進行測試
WX20170912-145816@2x.png
這些都是28*28的圖片
測試代碼如下
from keras.models import load_model
import numpy as np
from PIL import Image


def ImageToMatrix(filename):
    im = Image.open(filename)
    #change to greyimage
    im=im.convert("L")
    data = im.getdata()
    data = np.matrix(data,dtype='int')
    return data

model = load_model('/Users/zhang/Desktop/my_model.h5')


while 1:
    i = input('number:')
    j = input('type:')
    data = ImageToMatrix('/Users/zhang/Desktop/picture/'+str(i)+'_'+str(j)+'.png')
    data = np.array(data)
    data = data.reshape(1, 28, 28, 1)
    print 'test['+str(i)+'_'+str(j)+'], num='+str(i)+':'
    print model.predict_classes(
        data, batch_size=1, verbose=0
    )
選取了幾個結果
number:7
type:1
test[7_1], num=7:
[7]

number:7
type:2
test[7_2], num=7:
[7]

number:7
type:3
test[7_3], num=7:
[7]

number:2
type:1
test[2_1], num=2:
[2]

number:1
type:1
test[1_1], num=1:
[4]

number:1
type:2
test[1_2], num=1:
[1]

number:1
type:3
test[1_3], num=1:
[1]

number:6
type:1
test[6_1], num=6:
[5]

總結:

  • 該模型對于小字體沒法正常識別(和訓練集字體大小有關)
  • 對于類似 '1' 等數字服协,如果放在圖片邊緣,如:1_1啦粹,沒法準確識別
  • 當然偿荷,對于顛倒方向,橫放豎放的數字也沒法準確識別
  • 在mnist的測試集中唠椭,可以說是10000張圖片只有大約200張識別錯誤

改進方案

  • 對讀取進來的圖片進行先行處理(顛倒跳纳,居中,縮放等等),使得識別更加容易
  • 對訓練集進行處理贪嫂,使用不同方向的數字訓練集(訓練量加大)
  • 對神經層進行改進(由于沒有深入了解寺庄,其實這次的神經網絡也是瞎編的,只不過使用了卷積層和全連接層的結合)
推薦李宏毅的機器學習的視頻(youtube:李宏毅)
最后編輯于
?著作權歸作者所有,轉載或內容合作請聯(lián)系作者
  • 序言:七十年代末力崇,一起剝皮案震驚了整個濱河市斗塘,隨后出現(xiàn)的幾起案子,更是在濱河造成了極大的恐慌亮靴,老刑警劉巖馍盟,帶你破解...
    沈念sama閱讀 222,627評論 6 517
  • 序言:濱河連續(xù)發(fā)生了三起死亡事件,死亡現(xiàn)場離奇詭異台猴,居然都是意外死亡朽合,警方通過查閱死者的電腦和手機俱两,發(fā)現(xiàn)死者居然都...
    沈念sama閱讀 95,180評論 3 399
  • 文/潘曉璐 我一進店門,熙熙樓的掌柜王于貴愁眉苦臉地迎上來曹步,“玉大人宪彩,你說我怎么就攤上這事〗不椋” “怎么了尿孔?”我有些...
    開封第一講書人閱讀 169,346評論 0 362
  • 文/不壞的土叔 我叫張陵,是天一觀的道長筹麸。 經常有香客問我活合,道長,這世上最難降的妖魔是什么物赶? 我笑而不...
    開封第一講書人閱讀 60,097評論 1 300
  • 正文 為了忘掉前任白指,我火速辦了婚禮,結果婚禮上酵紫,老公的妹妹穿的比我還像新娘告嘲。我一直安慰自己,他們只是感情好奖地,可當我...
    茶點故事閱讀 69,100評論 6 398
  • 文/花漫 我一把揭開白布橄唬。 她就那樣靜靜地躺著,像睡著了一般参歹。 火紅的嫁衣襯著肌膚如雪仰楚。 梳的紋絲不亂的頭發(fā)上,一...
    開封第一講書人閱讀 52,696評論 1 312
  • 那天犬庇,我揣著相機與錄音僧界,去河邊找鬼。 笑死械筛,一個胖子當著我的面吹牛捎泻,可吹牛的內容都是我干的。 我是一名探鬼主播埋哟,決...
    沈念sama閱讀 41,165評論 3 422
  • 文/蒼蘭香墨 我猛地睜開眼笆豁,長吁一口氣:“原來是場噩夢啊……” “哼!你這毒婦竟也來了赤赊?” 一聲冷哼從身側響起闯狱,我...
    開封第一講書人閱讀 40,108評論 0 277
  • 序言:老撾萬榮一對情侶失蹤,失蹤者是張志新(化名)和其女友劉穎抛计,沒想到半個月后哄孤,有當地人在樹林里發(fā)現(xiàn)了一具尸體,經...
    沈念sama閱讀 46,646評論 1 319
  • 正文 獨居荒郊野嶺守林人離奇死亡吹截,尸身上長有42處帶血的膿包…… 初始之章·張勛 以下內容為張勛視角 年9月15日...
    茶點故事閱讀 38,709評論 3 342
  • 正文 我和宋清朗相戀三年瘦陈,在試婚紗的時候發(fā)現(xiàn)自己被綠了凝危。 大學時的朋友給我發(fā)了我未婚夫和他白月光在一起吃飯的照片。...
    茶點故事閱讀 40,861評論 1 353
  • 序言:一個原本活蹦亂跳的男人離奇死亡晨逝,死狀恐怖蛾默,靈堂內的尸體忽然破棺而出,到底是詐尸還是另有隱情捉貌,我是刑警寧澤支鸡,帶...
    沈念sama閱讀 36,527評論 5 351
  • 正文 年R本政府宣布,位于F島的核電站趁窃,受9級特大地震影響牧挣,放射性物質發(fā)生泄漏。R本人自食惡果不足惜醒陆,卻給世界環(huán)境...
    茶點故事閱讀 42,196評論 3 336
  • 文/蒙蒙 一瀑构、第九天 我趴在偏房一處隱蔽的房頂上張望。 院中可真熱鬧统求,春花似錦检碗、人聲如沸。這莊子的主人今日做“春日...
    開封第一講書人閱讀 32,698評論 0 25
  • 文/蒼蘭香墨 我抬頭看了看天上的太陽另假。三九已至像屋,卻和暖如春,著一層夾襖步出監(jiān)牢的瞬間边篮,已是汗流浹背己莺。 一陣腳步聲響...
    開封第一講書人閱讀 33,804評論 1 274
  • 我被黑心中介騙來泰國打工, 沒想到剛下飛機就差點兒被人妖公主榨干…… 1. 我叫王不留戈轿,地道東北人凌受。 一個月前我還...
    沈念sama閱讀 49,287評論 3 379
  • 正文 我出身青樓,卻偏偏與公主長得像思杯,于是被迫代替她去往敵國和親胜蛉。 傳聞我的和親對象是個殘疾皇子,可洞房花燭夜當晚...
    茶點故事閱讀 45,860評論 2 361

推薦閱讀更多精彩內容