tensorflow训练好的模型预测

软件发布|下载排行|最新软件

当前位置:首页IT学院IT技术

tensorflow训练好的模型预测

Bubbliiiing   2022-06-03 我要评论

学习前言

在神经网络学习中slim常用函数与如何训练、保存模型文章里已经讲述了如何使用slim训练出来一个模型,这篇文章将会讲述如何预测。

载入模型思路

载入模型的过程主要分为以下四步:

1、建立会话Session;

2、将img_input的placeholder传入网络,建立网络结构;

3、初始化所有变量;

4、利用saver对象restore载入所有参数。

这里要注意的重点是,在利用saver对象restore载入所有参数之前,必须要建立网络结构,因为网络结构对应着cpkt文件中的参数。

(网络层具有对应的名称scope。)

实现代码

在运行实验代码前,可以直接下载代码,因为存在许多依赖的文件

import tensorflow as tf
import numpy as np
from nets import Net
from tensorflow.examples.tutorials.mnist import input_data
def compute_accuracy(x_data,y_data):
    global prediction
    y_pre = sess.run(prediction,feed_dict={img_input:x_data})
    correct_prediction = tf.equal(tf.arg_max(y_data,1),tf.arg_max(y_pre,1))
    accuracy = tf.reduce_mean(tf.cast(correct_prediction,tf.float32))
    result = sess.run(accuracy,feed_dict = {img_input:x_data})
    return result
mnist = input_data.read_data_sets("MNIST_data",one_hot = "true")
slim = tf.contrib.slim
# img_input的placeholder
img_input = tf.placeholder(tf.float32, shape = (None, 784))
img_reshape = tf.reshape(img_input,shape = (-1,28,28,1))
# 载入模型
sess = tf.Session()
Conv_Net = Net.Conv_Net()
# 将img_input的placeholder传入网络
prediction = Conv_Net.net(img_reshape)
# 载入模型
ckpt_filename = './logs/model.ckpt-20000'
# 初始化所有变量
sess.run(tf.global_variables_initializer())
saver = tf.train.Saver()
# 恢复
saver.restore(sess, ckpt_filename)
print(compute_accuracy(mnist.test.images,mnist.test.labels))

运行结果为:

0.9921

Copyright 2022 版权所有 软件发布 访问手机版

声明:所有软件和文章来自软件开发商或者作者 如有异议 请与本站联系 联系我们