keras实现手写数字识别(数据集:MNIST)

准备工作

  • keras
  • tensorflow
  • numpy
  • PIL

下载MNIST数据集

from keras.dataset import mnist

mnist.load_data(path)

path是保存的路径

模型结构

model1.png

这个模型用了两个Convolution2D层,两个MaxPooling2D层,一个Flatten层,两个全连接Dense层,使用的激活函数是relu,优化器是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来说,如果从一开始没有跑出最优值,可能就进入了死胡同,导致训练的准确率一直只有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:李宏毅)
最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
  • 序言:七十年代末,一起剥皮案震惊了整个滨河市,随后出现的几起案子,更是在滨河造成了极大的恐慌,老刑警刘岩,带你破解...
    沈念sama阅读 158,736评论 4 362
  • 序言:滨河连续发生了三起死亡事件,死亡现场离奇诡异,居然都是意外死亡,警方通过查阅死者的电脑和手机,发现死者居然都...
    沈念sama阅读 67,167评论 1 291
  • 文/潘晓璐 我一进店门,熙熙楼的掌柜王于贵愁眉苦脸地迎上来,“玉大人,你说我怎么就摊上这事。” “怎么了?”我有些...
    开封第一讲书人阅读 108,442评论 0 243
  • 文/不坏的土叔 我叫张陵,是天一观的道长。 经常有香客问我,道长,这世上最难降的妖魔是什么? 我笑而不...
    开封第一讲书人阅读 43,902评论 0 204
  • 正文 为了忘掉前任,我火速办了婚礼,结果婚礼上,老公的妹妹穿的比我还像新娘。我一直安慰自己,他们只是感情好,可当我...
    茶点故事阅读 52,302评论 3 287
  • 文/花漫 我一把揭开白布。 她就那样静静地躺着,像睡着了一般。 火红的嫁衣衬着肌肤如雪。 梳的纹丝不乱的头发上,一...
    开封第一讲书人阅读 40,573评论 1 216
  • 那天,我揣着相机与录音,去河边找鬼。 笑死,一个胖子当着我的面吹牛,可吹牛的内容都是我干的。 我是一名探鬼主播,决...
    沈念sama阅读 31,847评论 2 312
  • 文/苍兰香墨 我猛地睁开眼,长吁一口气:“原来是场噩梦啊……” “哼!你这毒妇竟也来了?” 一声冷哼从身侧响起,我...
    开封第一讲书人阅读 30,562评论 0 197
  • 序言:老挝万荣一对情侣失踪,失踪者是张志新(化名)和其女友刘颖,没想到半个月后,有当地人在树林里发现了一具尸体,经...
    沈念sama阅读 34,260评论 1 241
  • 正文 独居荒郊野岭守林人离奇死亡,尸身上长有42处带血的脓包…… 初始之章·张勋 以下内容为张勋视角 年9月15日...
    茶点故事阅读 30,531评论 2 245
  • 正文 我和宋清朗相恋三年,在试婚纱的时候发现自己被绿了。 大学时的朋友给我发了我未婚夫和他白月光在一起吃饭的照片。...
    茶点故事阅读 32,021评论 1 258
  • 序言:一个原本活蹦乱跳的男人离奇死亡,死状恐怖,灵堂内的尸体忽然破棺而出,到底是诈尸还是另有隐情,我是刑警宁泽,带...
    沈念sama阅读 28,367评论 2 253
  • 正文 年R本政府宣布,位于F岛的核电站,受9级特大地震影响,放射性物质发生泄漏。R本人自食恶果不足惜,却给世界环境...
    茶点故事阅读 33,016评论 3 235
  • 文/蒙蒙 一、第九天 我趴在偏房一处隐蔽的房顶上张望。 院中可真热闹,春花似锦、人声如沸。这庄子的主人今日做“春日...
    开封第一讲书人阅读 26,068评论 0 8
  • 文/苍兰香墨 我抬头看了看天上的太阳。三九已至,却和暖如春,着一层夹袄步出监牢的瞬间,已是汗流浃背。 一阵脚步声响...
    开封第一讲书人阅读 26,827评论 0 194
  • 我被黑心中介骗来泰国打工, 没想到刚下飞机就差点儿被人妖公主榨干…… 1. 我叫王不留,地道东北人。 一个月前我还...
    沈念sama阅读 35,610评论 2 274
  • 正文 我出身青楼,却偏偏与公主长得像,于是被迫代替她去往敌国和亲。 传闻我的和亲对象是个残疾皇子,可洞房花烛夜当晚...
    茶点故事阅读 35,514评论 2 269

推荐阅读更多精彩内容