调用已经训练好的模型参数,预测手写数字。
from PIL import Image
import numpy as np
import tensorflow as tf
model_save_path = './checkpoint/mnist.ckpt'
# 复现模型
model = tf.keras.models.Sequential([
tf.keras.layers.Flatten(),
tf.keras.layers.Dense(128, activation='relu'),
tf.keras.layers.Dense(10, activation='softmax')])
# 加载模型权重
model.load_weights(model_save_path)
preNum = int(input("input the number of test pictures:"))
for i in range(preNum):
image_path = input("the path of test picture:")
img = Image.open(image_path)
# 重新定义输入大小,以便和训练的模型输入相同
img = img.resize((28, 28), Image.ANTIALIAS)
# 模型转灰度
img_arr = np.array(img.convert('L'))
# *********************图片预处理
img_arr = 255 - img_arr
"""
for i in range(28):
for j in range(28):
if img_arr[i][j] < 200:
img_arr[i][j] = 255
else:
img_arr[i][j] = 0
"""
# *********************图片预处理
# 归一化
img_arr = img_arr / 255.0
print("img_arr:", img_arr.shape)
# 升维度
# 为什么要升维度:由于predict是按照batch作为输入的,在这里batch是1,即我们输入的那张图片,所以应该要升维度1,且该维度在最前面
x_predict = img_arr[tf.newaxis, ...]
print("x_predict:", x_predict.shape)
result = model.predict(x_predict)
pred = tf.argmax(result, axis=1)
print('\n')
tf.print(pred)
代码中的几个注意点:
图像加载已经训练好的模型,需要设定输入的形状shape,并转灰度:
# 重新定义输入大小,以便和训练的模型输入相同,设定ANTIALIAS,即抗锯齿
预测的时候需要升维度:
# 为什么要升维度:由于predict是按照batch作为输入的,在这里batch是1,即我们输入的那张图片,所以应该要升维度1,且该维度在最前面