利用 tensorflow2.0 进行手写数字识别 并进行预测识别 保存模型

1·构建并训练模型

import tensorflow as tf
from PIL import Image
import numpy as np
import matplotlib.pyplot as plt 
import pandas as pd

mnist = tf.keras.datasets.mnist
#载入 MNIST 数据集,并将整型转换为浮点型,除以 255 是为了归一化。
(x_train, y_train), (x_test, y_test) = mnist.load_data()
x_train, x_test = x_train / 255.0, x_test / 255.0

#使用 tf.keras.Sequential 建立模型,并且选择优化器和损失函数
model = tf.keras.models.Sequential([
  tf.keras.layers.Flatten(input_shape=(28, 28)),
  tf.keras.layers.Dense(128, activation='relu'),
  tf.keras.layers.Dropout(0.2),
  tf.keras.layers.Dense(10, activation='softmax')
])

model.compile(optimizer='adam',
              loss='sparse_categorical_crossentropy',
              metrics=['accuracy'])


#训练模型
history = model.fit(x_train, y_train, epochs=10,validation_data=(x_test,y_test))

2·对模型进行评估

#模型评估
model.evaluate(x_test,  y_test, verbose=2)

#查看训练集与测试集的均方误差和准确率变化情况
history.history.keys()

plt.plot(history.epoch,history.history.get('loss'),label='loss')
plt.plot(history.epoch,history.history.get('val_loss'),label='val_loss')
plt.legend()
plt.show()

plt.plot(history.epoch,history.history.get('accuracy'),label='accuracy')
plt.plot(history.epoch,history.history.get('val_accuracy'),label='val_accuracy')
plt.legend()
plt.show()

3·保存并调用模型进行手写数字图片的识别

# 保存全模型
model.save('tf_model.h5')
#调用模型
new_model = tf.keras.models.load_model('tf_model.h5')

#调用模型进行预测识别
im = Image.open(r"D:\个人文件\Desktop\6.png")  #读取图片路径
im = im.resize((28,28)) #调整大小和模型输入大小一致
im = np.array(im)

#对图片进行灰度化处理
p3 = im.min(axis = -1)
plt.imshow(p3,cmap = 'gray')

#将白底黑字变成黑底白字   由于训练模型是这种格式
for i in range(28):
    for j in range(28):
        p3[i][j] = 255-p3[i][j]

#模型输出结果是每个类别的概率,取最大的概率的类别就是预测的结果
ret = new_model.predict((p3/255).reshape((1,28,28)))
number = np.argmax(ret)

发布了49 篇原创文章 · 获赞 13 · 访问量 2万+

猜你喜欢

转载自blog.csdn.net/weixin_44166997/article/details/103034683