您的位置:首页 > 其它

tensorflow模型参数与结构的保存-----二

2018-01-07 15:09 489 查看
   由于前面介绍过tf.train.Saver类的模型与保护,但是该方法仅仅只是对模型参数的保存,对于模型的结构没有保存,也就是说,我们每次在加载tf.train.Saver类保存的模型都要讲模型结构重新写一遍,这样就显得过于繁琐,对于以上问题,tensorflow 提供了convert_variables_to_constants函数,通过这个函数可以将模型结构与变量全部保存在一个文件夹中,本篇还是以MNIST例子为例,给出模型保存的代码,代码如下所示:

import tensorflow as tf
from tensorflow.examples.tutorials.mnist import input_data

#载入数据集
mnist = input_data.read_data_sets("MNIST_data",one_hot=True)

#每个批次100张照片
batch_size = 100
#计算一共有多少个批次
n_batch = mnist.train.num_examples // batch_size

#定义两个placeholder
x = tf.placeholder(tf.float32,[None,784],name='x-input')
y = tf.placeholder(tf.float32,[None,10])

#创建一个简单的神经网络,输入层784个神经元,输出层10个神经元
W = tf.Variable(tf.zeros([784,10]))
b = tf.Variable(tf.zeros([10]))
prediction = tf.nn.softmax(tf.matmul(x,W)+b, name='output')

#二次代价函数
# loss = tf.reduce_mean(tf.square(y-prediction))
loss = tf.reduce_mean(tf.nn.softmax_cross_entropy_with_logits(labels=y,logits=prediction))
#使用梯度下降法
train_step = tf.train.GradientDescentOptimizer(0.2).minimize(loss)

#初始化变量
init = tf.global_variables_initializer()

#结果存放在一个布尔型列表中
correct_prediction = tf.equal(tf.argmax(y,1),tf.argmax(prediction,1))#argmax返回一维张量中最大的值所在的位置
#求准确率
accuracy = tf.reduce_mean(tf.cast(correct_prediction,tf.float32))

with tf.Session() as sess:
    sess.run(init)
    for epoch in range(11):
        for batch in range(n_batch):
            batch_xs,batch_ys =  mnist.train.next_batch(batch_size)
            sess.run(train_step,feed_di
4000
ct={x:batch_xs,y:batch_ys})
        
        acc = sess.run(accuracy,feed_dict={x:mnist.test.images,y:mnist.test.labels})
        print("Iter " + str(epoch) + ",Testing Accuracy " + str(acc))
    #保存模型参数和结构
    output_graph_def = tf.graph_util.convert_variables_to_constants(sess,sess.graph_def,output_node_names = ['output'])
    # 保存模型到目录下的model文件夹中
    with tf.gfile.FastGFile('./models/tfmodel.pb',mode='wb') as f:
        f.write(output_graph_def.SerializeToString())

显示结果如下所示:

内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: