应用程序,给图识物
博主微信公众号(左)、Python+智能大数据+AI学习交流群(右):欢迎关注和加群,大家一起学习交流,共同进步!
目录
摘要
应用程序,给图识物
一、给图识物
输入一张手写数字图片:
神经网络自动识别出值:
手写 10 个数字,正确率 90% 以上合格。
二、前向传播执行应用
predict(输入数据, batch_size=整数) # 返回前向传播计算结果
实现前向传播执行识图应用三步骤:
(1)复现模型(前向传播)
model = tf.keras.Sequential([
tf.keras.layers.Flatten(),
tf.keras.layers.Dense(128, activation="relu"),
tf.keras.layers.Dense(10, activation="softmax")
])
(2)参数加载
model.load_weights(model_save_path)
(3)预测结果
result = model.predict(x_predict)
注:predict 参数详解。
(1)x:输入数据,Numpy 数组(或者 Numpy 数组的列表,如果模型有多个输出);
(2)batch_size:整数,由于 GPU 的特性,batch_size 最好选用 8, 16, 32, 64 ......,如果未指定,默认为32;
(3)verbose:日志显示模式,0 或 1;
(4)steps:声明预测结束之前的总步数(批次样本),默认值 None;
(5)返回:预测的 Numpy 数组(或数组列表)。
三、完整代码
"""
应用程序,给图识物
"""
# 模块导入
import os
import numpy as np
import tensorflow as tf
from PIL import Image
# 获取模型存储路径
# ../MNIST_FC/checkpoint/mnist.ckpt
base_path = os.path.dirname(os.path.abspath(__file__))
base_path = os.path.join(base_path, "MNIST_FC")
checkpoint_path = os.path.join(base_path, "checkpoint")
model_save_path = os.path.join(checkpoint_path, "mnist.ckpt")
# 复现模型
model = tf.keras.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:")
image_path = os.path.join(base_path, image_path)
# 打开图片
img = Image.open(image_path)
# 调整尺寸
# 因为训练模型时使用的是28行28列的灰度图,输入是任意尺寸的图片,需要先resize成28行28列的标准尺寸
img = img.resize((28, 28), Image.ANTIALIAS)
# 调整类型,转换为灰度图
img_arr = np.array(img.convert("L"))
# 图片预处理
# 方案一:
# 应用程序的输入图片时白底黑字,但训练模型时用的训练集是黑底白字灰度图,
# 所以需要让每个像素点等于255减去当前像素值,相当于颜色取反。
# 这个操作使得输入的从未见过的图片,满足了神经网络模型对输入风格的要求,这个过程叫做预处理。
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 # 纯黑色
# 对图片数据除以255归一化
img_arr = img_arr / 255.0
print(f"img_arr: {img_arr.shape}")
# (28, 28) ==> (1, 28, 28)
x_predict = img_arr[tf.newaxis, ...]
print(f"x_predict: {x_predict.shape}")
# 预测
result = model.predict(x_predict)
# 输出最大的概率值
pred = tf.argmax(result, axis=1)
print("\n")
tf.print(pred)