keras之分类数字图片(二)

0 前言

要求:

1 搭建模型

目标:

  • 使用keras搭建简单的网络结构,用来预测mnist数据集中的手写数字

步骤:

  1. 从MNIST加载图片数据。
  2. 数据进行预处理
  3. 构建网络模型,模型结构如下图
  4. 模型结构可视化
  5. 模型性能评估以及预测
  6. 保存模型及参数,以便下次直接使用
在这里插入图片描述

1.1、加载数据

import numpy as np
from keras.models import Sequential
from keras.layers import Dense, Dropout, Activation, Flatten
from keras.layers import Conv2D, MaxPooling2D
from keras.utils import np_utils
from keras.datasets import mnist

# 加载mnist数据集
(x_train, y_train), (x_test, y_test) = mnist.load_data()
# train中有6万张手写数字图片,test中有1万张手写数字图片
print (x_train.shape)
print (x_test.shape)

运行结果:


在这里插入图片描述

1.2、数据进行预处理

# 进行one-hot(独热编码)
# 进行one-hot编码是因为损失函数需要使用交叉嫡函数(cross_entropy)
# 交叉嫡函数详解  https://zhuanlan.zhihu.com/p/35709485 
y_train = np_utils.to_categorical(y_train,10)
y_test = np_utils.to_categorical(y_test,10)
# 由于下载数据得到是uint类型,在神经网络无法进行合理运算,在这里将其转化为float32类型
x_train = x_train.astype(np.float32)
x_test = x_test.astype(np.float32)
# 由于conv2D函数需要这四维的图片数据,这里就reshape维度
x_train = x_train.reshape([-1,28,28,1])
x_test = x_test.reshape([-1,28,28,1])

np_utils.to_categorical(y_train,10),即进行独热编码,解释如下代码:

import matplotlib.pyplot as plt
from keras.utils import np_utils
# 以下说明to_categorical作用,相当于进行one-hot(独热编码)
print(np_utils.to_categorical([5,6,7],8))

运行结果:


在这里插入图片描述

1.3、构建网络模型

# 选择线性结构的网络模型
model = Sequential()

# 使用Conv2D函数的padding参数默认为‘valid’
# 默认使用valid
# For the VALID padding, the output height and width are computed as:
# out_height = ceil(float(in_height - filter_height + 1) / float(strides[1]))

# For the SAME padding, the output height and width are computed as:
# out_height = ceil(float(in_height) / float(strides[1]))
# 知道padding以上“valid”和“same”两种模式,就能知道通过一个卷积层后,
# 模型的输出结构了
model.add(Conv2D(32, (3, 3), activation='relu', input_shape=(28, 28, 1)))
print (model.output_shape)
model.add(Conv2D(32, (3, 3), activation='relu'))
print (model.output_shape)
model.add(MaxPooling2D(pool_size=(2,2)))
print (model.output_shape)
model.add(Dropout(0.25))
print (model.output_shape)

model.add(Flatten())
print (model.output_shape)
model.add(Dense(100,activation="relu"))
print (model.output_shape)
model.add(Dropout(0.5))
print (model.output_shape)
model.add(Dense(10,activation="softmax"))
print (model.output_shape)

# 模型的损失函数使用交叉嫡函数,优化器使用“sgd”,即随机梯度下降
# 梯度下降详解  https://baijiahao.baidu.com/s?id=1613121229156499765&wfr=spider&for=pc
model.compile(loss="categorical_crossentropy",optimizer="sgd",metrics="acc")
model.fit(x_train,y_train,batch_size=64,epochs=10)

运行结果:


在这里插入图片描述

1.4、模型可视化

from keras.utils import plot_model
plot_model(model,show_shapes=True)
print (model.summary())

运行结果:


在这里插入图片描述
在这里插入图片描述

1.5、模型评估及预测

  • 1、模型评估:
# 使用测试集合检验模型性能
loss = model.evaluate(x_test,y_test)
print (loss)

运行结果:


在这里插入图片描述
  • 2、模型预测
import numpy as np
import matplotlib.pyplot as plt
# 为了方便显示,这里就显示测试集中前两个预测结果
for i in range(2):
  plt.imshow(x_test[i].reshape((28,28)))
  plt.show()
  print(x_test[i].shape)
# 这里预测接收的结构也是四维的,故reshape
  y_pred = model.predict(x_test[i].reshape(1,28,28,1))
  print(y_pred)
  print(np.argmax(y_pred))

运行结果:


在这里插入图片描述

1.6、保存模型及参数

from datetime import datetime
# 暂时保存模型为h5文件
file_name = datetime.now().strftime("dentify_writtern_number_%Y%m%d_%H%M/epoch:10-loss:0.2525.h5")
model.save(file_name)

运行无结果。生成文件截图如下:


在这里插入图片描述

2 源代码

# 1、加载mnist数据集
import numpy as np
from keras.models import Sequential
from keras.layers import Dense, Dropout, Activation, Flatten
from keras.layers import Conv2D, MaxPooling2D
from keras.utils import np_utils
from keras.datasets import mnist

# 加载mnist数据集
(x_train, y_train), (x_test, y_test) = mnist.load_data()
# train中有6万张手写数字图片,test中有1万张手写数字图片
print (x_train.shape)
print (x_test.shape)


# 2、数据预处理
# 进行one-hot(独热编码)
# 进行one-hot编码是因为损失函数需要使用交叉嫡函数(cross_entropy)
# 交叉嫡函数详解  https://zhuanlan.zhihu.com/p/35709485 
y_train = np_utils.to_categorical(y_train,10)
y_test = np_utils.to_categorical(y_test,10)
# 由于下载数据得到是uint类型,在神经网络无法进行合理运算,在这里将其转化为float32类型
x_train = x_train.astype(np.float32)
x_test = x_test.astype(np.float32)
# 由于conv2D函数需要这四维的图片数据,这里就reshape维度
x_train = x_train.reshape([-1,28,28,1])
x_test = x_test.reshape([-1,28,28,1])

import matplotlib.pyplot as plt
from keras.utils import np_utils
# 以下说明to_categorical作用,相当于进行one-hot(独热编码)
print(np_utils.to_categorical([5,6,7],8))


# 3、构建网络结构
# 选择线性结构的网络模型
model = Sequential()
# 使用Conv2D函数的padding参数默认为‘valid’
# 默认使用valid
# For the VALID padding, the output height and width are computed as:
# out_height = ceil(float(in_height - filter_height + 1) / float(strides[1]))

# For the SAME padding, the output height and width are computed as:
# out_height = ceil(float(in_height) / float(strides[1]))
# 知道padding以上“valid”和“same”两种模式,就能知道通过一个卷积层后,
# 模型的输出结构了
model.add(Conv2D(32, (3, 3), activation='relu', input_shape=(28, 28, 1)))
print (model.output_shape)
model.add(Conv2D(32, (3, 3), activation='relu'))
print (model.output_shape)
model.add(MaxPooling2D(pool_size=(2,2)))
print (model.output_shape)
model.add(Dropout(0.25))
print (model.output_shape)

model.add(Flatten())
print (model.output_shape)
model.add(Dense(100,activation="relu"))
print (model.output_shape)
model.add(Dropout(0.5))
print (model.output_shape)
model.add(Dense(10,activation="softmax"))
print (model.output_shape)

# 模型的损失函数使用交叉嫡函数,优化器使用“sgd”,即随机梯度下降
# 梯度下降详解  https://baijiahao.baidu.com/s?id=1613121229156499765&wfr=spider&for=pc
model.compile(loss="categorical_crossentropy",optimizer="sgd",metrics="acc")
model.fit(x_train,y_train,batch_size=64,epochs=10)


# 4、模型可视化
from keras.utils import plot_model
plot_model(model,show_shapes=True)
print (model.summary())


# 5、模型评估及预测 
# 使用测试集合检验模型性能
loss = model.evaluate(x_test,y_test)
print (loss)

import numpy as np
import matplotlib.pyplot as plt
# 为了方便显示,这里就显示测试集中前两个预测结果
for i in range(2):
  plt.imshow(x_test[i].reshape((28,28)))
  plt.show()
  print(x_test[i].shape)
# 这里预测接收的结构也是四维的,故reshape
  y_pred = model.predict(x_test[i].reshape(1,28,28,1))
  print(y_pred)
  print(np.argmax(y_pred))


# 6、模型保存
from datetime import datetime
# 暂时保存模型为h5文件
file_name = datetime.now().strftime("dentify_writtern_number_%Y%m%d_%H%M/epoch:10-loss:0.2525.h5")
model.save(file_name)

如有疑惑,以下评论区留言。力所能及,必答之。

©著作权归作者所有,转载或内容合作请联系作者
  • 序言:七十年代末,一起剥皮案震惊了整个滨河市,随后出现的几起案子,更是在滨河造成了极大的恐慌,老刑警刘岩,带你破解...
    沈念sama阅读 219,589评论 6 508
  • 序言:滨河连续发生了三起死亡事件,死亡现场离奇诡异,居然都是意外死亡,警方通过查阅死者的电脑和手机,发现死者居然都...
    沈念sama阅读 93,615评论 3 396
  • 文/潘晓璐 我一进店门,熙熙楼的掌柜王于贵愁眉苦脸地迎上来,“玉大人,你说我怎么就摊上这事。” “怎么了?”我有些...
    开封第一讲书人阅读 165,933评论 0 356
  • 文/不坏的土叔 我叫张陵,是天一观的道长。 经常有香客问我,道长,这世上最难降的妖魔是什么? 我笑而不...
    开封第一讲书人阅读 58,976评论 1 295
  • 正文 为了忘掉前任,我火速办了婚礼,结果婚礼上,老公的妹妹穿的比我还像新娘。我一直安慰自己,他们只是感情好,可当我...
    茶点故事阅读 67,999评论 6 393
  • 文/花漫 我一把揭开白布。 她就那样静静地躺着,像睡着了一般。 火红的嫁衣衬着肌肤如雪。 梳的纹丝不乱的头发上,一...
    开封第一讲书人阅读 51,775评论 1 307
  • 那天,我揣着相机与录音,去河边找鬼。 笑死,一个胖子当着我的面吹牛,可吹牛的内容都是我干的。 我是一名探鬼主播,决...
    沈念sama阅读 40,474评论 3 420
  • 文/苍兰香墨 我猛地睁开眼,长吁一口气:“原来是场噩梦啊……” “哼!你这毒妇竟也来了?” 一声冷哼从身侧响起,我...
    开封第一讲书人阅读 39,359评论 0 276
  • 序言:老挝万荣一对情侣失踪,失踪者是张志新(化名)和其女友刘颖,没想到半个月后,有当地人在树林里发现了一具尸体,经...
    沈念sama阅读 45,854评论 1 317
  • 正文 独居荒郊野岭守林人离奇死亡,尸身上长有42处带血的脓包…… 初始之章·张勋 以下内容为张勋视角 年9月15日...
    茶点故事阅读 38,007评论 3 338
  • 正文 我和宋清朗相恋三年,在试婚纱的时候发现自己被绿了。 大学时的朋友给我发了我未婚夫和他白月光在一起吃饭的照片。...
    茶点故事阅读 40,146评论 1 351
  • 序言:一个原本活蹦乱跳的男人离奇死亡,死状恐怖,灵堂内的尸体忽然破棺而出,到底是诈尸还是另有隐情,我是刑警宁泽,带...
    沈念sama阅读 35,826评论 5 346
  • 正文 年R本政府宣布,位于F岛的核电站,受9级特大地震影响,放射性物质发生泄漏。R本人自食恶果不足惜,却给世界环境...
    茶点故事阅读 41,484评论 3 331
  • 文/蒙蒙 一、第九天 我趴在偏房一处隐蔽的房顶上张望。 院中可真热闹,春花似锦、人声如沸。这庄子的主人今日做“春日...
    开封第一讲书人阅读 32,029评论 0 22
  • 文/苍兰香墨 我抬头看了看天上的太阳。三九已至,却和暖如春,着一层夹袄步出监牢的瞬间,已是汗流浃背。 一阵脚步声响...
    开封第一讲书人阅读 33,153评论 1 272
  • 我被黑心中介骗来泰国打工, 没想到刚下飞机就差点儿被人妖公主榨干…… 1. 我叫王不留,地道东北人。 一个月前我还...
    沈念sama阅读 48,420评论 3 373
  • 正文 我出身青楼,却偏偏与公主长得像,于是被迫代替她去往敌国和亲。 传闻我的和亲对象是个残疾皇子,可洞房花烛夜当晚...
    茶点故事阅读 45,107评论 2 356

推荐阅读更多精彩内容