如何利用神经网络制作一个识别手写数字的程序(以colab 平台作举例)

如何利用神经网络制作一个识别手写数字的程序(以colab 平台作举例)

前言: 本程序平台为 colab 即google的深度学习在线平台,为防止初学者被繁杂的tensflow 环境配置磨灭了热情, 我们不妨使用在线的深度学习平台进行学习和训练

点击这里即可 不过可能要科学上网 ,不能的同学也可以利用国内的平台,在结果上并无不同之处

image-20201121143617947

利用数据集mnist 进行手写数字的识别

废话不多说,让我们开始吧 ( 为了让大家更好的理解,每一步我都标注了比较详细的注释哈)

一:导入相关的包:

 !pip install tensorflow keras numpy mnist matplotlib
 # 导入数据包
import numpy as np
import mnist  # 获得数据集
import matplotlib.pyplot as plt  # Graph
from keras.models import Sequential  # ANN 网络结构
from keras.layers import Dense # the layer in  the  ANN
import keras
import keras.utils
from keras import utils as np_utils

二:导入mnist数据集中对应数据

# 导入数据
train_images = mnist.train_images()  # 训练数据集图片
train_labels = mnist.train_labels()   # 训练标签 
test_images = mnist.test_images()  # 测试图片
test_labels = mnist.test_labels()  # 测试标签

注:因为mnist 已经是一个分类好的 数据集了,我们只需要调用期中的训练数据和测试数据即可

三:对数据进行相应的处理,将图片数据归一化,同时向量化

# 规范化图片   规范化像素值[0,255]
# 为了使神经网络更好的训练,我们把值设置为[-0.5 , 0.5]
train_images = (train_images/255) - 0.5
test_images = (test_images/255) - 0.5
# 将 28 * 28 像素图片展成 28 * 28 = 784 维向量
train_images = train_images.reshape((-1,784))
test_images = test_images.reshape((-1,784))
#打印出来
print(train_images.shape) # 6000个训练数据
print(test_images.shape) # 1000个测试数据

结果是:

image-20201121143537482

四:建立神经网络模型

在这里我们为了方面初学者,我们使用 Keras Sequential 顺序模型

​ 顺序模型是多个网络层的线性堆叠。

你可以通过将网络层实例的列表传递给 Sequential 的构造器,来创建一个 Sequential 模型

官方中文doc指路

image-20201121141749110

# 建立模型
# 3层 ,其中两层 64 个神经元 以及激励函数  一层10个神经元 以及归一化指数函数(softmax fuction)
model = Sequential()
model.add( Dense(64, activation="relu", input_dim = 784))
model.add( Dense(64, activation="relu"))
model.add(Dense(10, activation="softmax"))
print(model.summary())

我们打印出来模型的简要介绍:

image-20201121135552582

五:进行模型的编译和训练

# 编译模型 
# 损失函数衡量模型在训练中的表现 然后进行优化
model.compile(
    optimizer = 'adam',
    loss = "categorical_crossentropy",
    metrics = ["accuracy"]
)
# 训练模型
from keras.utils.np_utils import to_categorical
history=model.fit(
    train_images,
    to_categorical(train_labels),
    epochs = 5,  #要训​​练的整个数据集的迭代次数
    batch_size = 32  #每个梯度更新的样本数以进行训练

)

print(history.history.keys())
# print(plt.plot(history.history['loss']))
print(plt.plot(history.history['accuracy']))

如果我上述注释大家有不明白之处,指路 我是官方文档,快来点我鸭

the result:

image-20201121140104287

看,我们的训练精读达到了百分之九十六左右,当然首次训练比较失败23333,但是随着训练次数的增加精度在上升了呢,你也可以增加迭代次数来得到更高的精度呀!

训练完成了以后,让我们小小评估一下这个模型吧

六:评估模型

# 评估模型
model.evaluate(
    test_images,
    to_categorical(test_labels)
)

the result :

image-20201121140537376

七 :进行预测

# 保存模型
# 预测前五个图片


predictions = model.predict(test_images[:5])
# 输出模型预测 同时和标准值进行比较
print(np.argmax(predictions, axis = 1))
print(test_labels[:5])

image-20201121141514189

结果完全正确! Amazing!

八:看看在mnist 中的图片长啥样?

for i in range(0,5):
  first_image = test_images[i]
  first_image = np.array(first_image ,dtype= "float")
  pixels = first_image.reshape((28 ,28))
  plt.imshow(pixels , cmap="gray")
  plt.show()

image-20201121141939835

image-20201121141952481

image-20201121142005260

看来效果还不错。

九:识别自己的手写体?

首先需要建立连接:

因为catlab 的文件运行在云端中,我需要它和google drives 进行绑定 ,在本地运行的同学则不用这个步骤

import os
from google.colab import drive
drive.mount('/content/drive')

path = "/content/drive/My Drive/data"

os.chdir(path)
os.listdir(path)

之后,进行模型预测

from PIL import Image
import numpy as np
import os

img = Image.open("test.jpg").convert("1")
img = np.resize(img, (28,28,1))
im2arr = np.array(img)
im2arr = im2arr.reshape(1,784)
y_pred = model.predict(im2arr)
print(np.argmax(y_pred, axis = 1))

结果:image-20201121142720135

结果应该是正确的,

这是我写的5,23333

fullsizerender(1).jpg)

附上源代码链接