基于已有神经网络模型的预测(tensorflow)

训练模型之后的预测:

predict(输入特征,batch_size=整数)
给出输入特征,输出预测结果
实现预测的三步:
1.复现模型:model=tf.keras.models.Sequential([…])
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'))

    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.0
    x_predict = img_arr[tf.newaxis, ...]
    result = model.predict(x_predict)

    pred = tf.argmax(result, axis=1)

    print('\n')
    tf.print(pred)

版权声明:本文为qq_57780419原创文章,遵循CC 4.0 BY-SA版权协议,转载请附上原文出处链接和本声明。