栏目分类:
子分类:
返回
名师互学网用户登录
快速导航关闭
当前搜索
当前分类
子分类
实用工具
热门搜索
名师互学网 > IT > 软件开发 > 后端开发 > Python

tensorflow笔记【8】深度学习-预测

Python 更新时间: 发布时间: IT归档 最新发布 模块sitemap 名妆网 法律咨询 聚返吧 英语巴士网 伯小乐 网商动力

tensorflow笔记【8】深度学习-预测

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()    # 关闭图片

总结
转载请注明:文章转载自 www.mshxw.com
本文地址:https://www.mshxw.com/it/972070.html
我们一直用心在做
关于我们 文章归档 网站地图 联系我们

版权所有 (c)2021-2022 MSHXW.COM

ICP备案号:晋ICP备2021003244-6号