tensorflow笔记【8】深度学习-预测
文章目录- 一、应用程序,给图识物
- 二、使用步骤
- 1.复现模型,前向传播
- 2.load_weight读取已有参数
- 3.使用predicth函数根据输入特征输出预测结果
- 总结
提示:以下是本篇文章正文内容,下面案例可供参考
一、应用程序,给图识物predict predict(x, batch_size=None, verbose=0, steps=None) 为输入样本生成输出预测。 计算是分批进行的 参数 x: 输入数据,Numpy 数组 (或者 Numpy 数组的列表,如果模型有多个输出)。 batch_size: 整数。如未指定,默认为 32。 verbose: 日志显示模式,0 或 1。 steps: 声明预测结束之前的总步数(批次样本)。默认值 None。 返回 预测的 Numpy 数组(或数组列表)。二、使用步骤 1.复现模型,前向传播 2.load_weight读取已有参数 3.使用predicth函数根据输入特征输出预测结果
代码如下:
# 1.导入相关模块---import
import matplotlib.pyplot as plt
from PIL import Image
import numpy as np
import tensorflow as tf
import os
from tensorflow.keras.layers import Flatten, Dense
from tensorflow.keras import Model
# 2.搭建网络模型----class
model_save_path = './checkpoint/checkpoint.ckpt' # 最优模型保存路径
class MnistModel(Model):
def __init__(self):
super(MnistModel, self).__init__()
self.flatten = Flatten()
self.d1 = Dense(128, activation='relu')
self.d2 = Dense(10, activation='softmax')
def call(self, x):
x = self.flatten(x)
x = self.d1(x)
y = self.d2(x)
return y
model = MnistModel()
# 3.加载参数---load_weight
model.load_weights(model_save_path)
# 4.预测输出结果---prdeict
# 预测图片的数量
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)
# 显示图片
image = plt.imread(image_path)
plt.set_cmap('gray')
plt.imshow(image)
# 调整输入神经网络的图片尺寸和类型
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
x_predict = img_arr[tf.newaxis, ...]
result = model.predict(x_predict)
pred = tf.argmax(result, axis=1) # 行
print('n')
tf.print(pred)
plt.pause(5) # 暂停一秒
plt.close() # 关闭图片
总结



