zoukankan      html  css  js  c++  java
  • 【tensorflow】神经网络:给图识物

    实现前向传播,给物识图仅需三步:

    复现模型

    加载参数

    预测结果

    # 复现模型
    mode = tf.keras.models.Sequential([
        tf.keras.layers.Flatten(),
        tf.keras.layers.Dense(128, activation="relu"),
        tf.keras.layers.Dense(10, activation="sotfmax")
    ])
    
    # 加载参数
    model.load_weight(checkpoint_save_path)
    
    # 预测结果
    result = model.predict(x_predict)

    代码:

    from PIL import Image
    import numpy as np
    import tensorflow as tf
    import matplotlib.pyplot as plt
    
    # 复现模型
    model = tf.keras.models.Sequential([
        tf.keras.layers.Flatten(),
        tf.keras.layers.Dense(128, activation="relu"),
        tf.keras.layers.Dense(10, activation="softmax")
    ])
    
    # 加载参数
    checkpoint_save_path = "class4/MNIST_FC/checkpoint/mnist.ckpt"
    model.load_weights(checkpoint_save_path)
    
    # 做10次预测
    for i in range(10):
        # 根据用户输入,读取图片
        image_path = "class4/MNIST_FC/" + 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
    
        # 归一化,减小计算量
        img_arr = img_arr/255.0
    
        # 由于训练数据是以batch为单位喂入神经网络训练的
        # 所以是三维数据(batch, 28, 28)
        # 需要给待预测图片添加维度
        x_predict = img_arr[tf.newaxis, ...]
    
        # 预测结果
        result = model.predict(x_predict)
    
        # 寻找概率最大的预测结果
        pred = tf.argmax(result, axis=1)
    
        tf.print(pred)
    
        plt.pause(1)
        plt.close()
  • 相关阅读:
    Oracle手工建库
    php如何在某个时间上加一天?一小时? 时间加减
    JavaScript:this是什么?
    ping广播地址会如何(转)
    用CSS3实现文字描边
    vue二十七:vue基础之过滤器
    vue二十六:vue基础之vue生命周期
    vue二十五:vue基础之单个元素过渡和多个元素过渡
    vue二十五:vue基础之slot插槽和具名插槽
    vue二十四:vue基础之动态组件
  • 原文地址:https://www.cnblogs.com/bjxqmy/p/13538905.html
Copyright © 2011-2022 走看看