由前面所学的知识我们已经掌握了神经网络的基础知识,但是要想模型可以使用,还需要编写一套 程序。实现给图识物。
tensorflow给出了predict函数,它可以根据输入的特征输出预测结果,由predict函数实现前向传播,执行识图的应用只需要三步分别如下所示:
- 复现模型(前向传播)
model = tf.keras.models.Sequential([
tf.keras.layers.Flatten(),
tf.keras.layer.Dense(128,activation='relu'),
tf.keras.layers.Dense(128, activation='softmax')
])
2.加载参数
model.load_weights(model_save_path)
3.预测结果
result=model.predict(x_predict)
整体识别程序
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
img_arr = img_arr / 255.0
x_predict = img_arr[tf.newaxis, ...]
result = model.predict(x_predict)
pred = tf.argmax(result, axis=1)
print('\n')
tf.print(pred)