温馨提示×

温馨提示×

您好,登录后才能下订单哦!

密码登录×
登录注册×
其他方式登录
点击 登录注册 即表示同意《亿速云用户服务条款》

如何使用Tensorflow模型实现预测

发布时间:2021-06-04 17:43:26 来源:亿速云 阅读:558 作者:Leah 栏目:开发技术

如何使用Tensorflow模型实现预测?针对这个问题,这篇文章详细介绍了相对应的分析和解答,希望可以帮助更多想解决这个问题的小伙伴找到更简单易行的方法。

模型文件:

如何使用Tensorflow模型实现预测

预测图片:

如何使用Tensorflow模型实现预测

这里直接贴代码,都有注释,应该很好理解

import tensorflow as tf
import inference
 
image_size = 128 # 输入层图片大小
 
# 模型保存的路径和文件名
MODEL_SAVE_PATH = "model/"
MODEL_NAME = "model.ckpt"
 
# 加载需要预测的图片
image_data = tf.gfile.FastGFile("./data/test/d.png", 'rb').read()
 
# 将图片格式转换成我们所需要的矩阵格式,第二个参数为1,代表1维
decode_image = tf.image.decode_png(image_data, 1)
 
# 再把数据格式转换成能运算的float32
decode_image = tf.image.convert_image_dtype(decode_image, tf.float32)
 
# 转换成指定的输入格式形状
image = tf.reshape(decode_image, [-1, image_size, image_size, 1])
 
# 定义预测结果为logit值最大的分类,这里是前向传播算法,也就是卷积层、池化层、全连接层那部分
test_logit = inference.inference(image, train=False, regularizer=None)
 
# 利用softmax来获取概率
probabilities = tf.nn.softmax(test_logit)
 
# 获取最大概率的标签位置
correct_prediction = tf.argmax(test_logit, 1)
 
# 定义Savar类
saver = tf.train.Saver()
 
with tf.Session() as sess:
  sess.run((tf.global_variables_initializer(), tf.local_variables_initializer()))
 
  # 加载检查点状态,这里会获取最新训练好的模型
  ckpt = tf.train.get_checkpoint_state(MODEL_SAVE_PATH)
  if ckpt and ckpt.model_checkpoint_path:
    # 加载模型和训练好的参数
    saver.restore(sess, ckpt.model_checkpoint_path)
    print("加载模型成功:" + ckpt.model_checkpoint_path)
 
    # 通过文件名得到模型保存时迭代的轮数.格式:model.ckpt-6000.data-00000-of-00001
    global_step = ckpt.model_checkpoint_path.split('/')[-1].split('-')[-1]
 
    # 获取预测结果
    probabilities, label = sess.run([probabilities, correct_prediction])
 
    # 获取此标签的概率
    probability = probabilities[0][label]
 
    print("After %s training step(s),validation label = %d, has %g probability" % (global_step, label, probability))
  else:
    print("模型加载失败!" + ckpt.model_checkpoint_path)

运行输出结果:

如何使用Tensorflow模型实现预测

(标签为3,概率为0.984478)

标签字典:

如何使用Tensorflow模型实现预测

3对应小写d,识别正确。

其他的图片的预测结果:

预测图片1:

如何使用Tensorflow模型实现预测

如何使用Tensorflow模型实现预测

标签字典:

如何使用Tensorflow模型实现预测

关于如何使用Tensorflow模型实现预测问题的解答就分享到这里了,希望以上内容可以对大家有一定的帮助,如果你还有很多疑惑没有解开,可以关注亿速云行业资讯频道了解更多相关知识。

向AI问一下细节

免责声明:本站发布的内容(图片、视频和文字)以原创、转载和分享为主,文章观点不代表本网站立场,如果涉及侵权请联系站长邮箱:is@yisu.com进行举报,并提供相关证据,一经查实,将立刻删除涉嫌侵权内容。

AI