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())
显示结果如下所示:
相关文章推荐
- Tensorflow学习教程------模型参数和网络结构保存且载入,输入一张手写数字图片判断是几
- 学习TensorFlow,保存学习到的网络结构参数并调用
- 【深度学习】tensorflow加载VGG16的网络结构和模型参数
- TensorFlow_MNIST 保存、恢复模型及参数
- tensorflow模型参数保存和加载问题
- tensorflow模型参数与结构的加载-----二
- tensorflow学习(4):保存模型Saver.save()的参数命名机制以及restore并创建手写字体识别引擎
- 16、TensorFLow 模型参数的保存与恢复
- 在tensorflow中保存模型参数
- 学习TensorFlow,保存学习到的网络结构参数并调用
- 学习TensorFlow,保存学习到的网络结构参数并调用
- [Deep Learning] TensorFlow模型、参数的保存与读取
- TensorFlow训练的模型参数(W和B)利用np.savez()保存和用cnpy库C++读取
- tensorflow中保存模型、加载模型做预测(不需要再定义网络结构)
- 解决tensorflow模型参数保存和加载的问题
- tensorflow:保存与读取网络结构,参数等
- TensorFlow 训练好模型参数的保存和恢复代码
- Tensorflow使用笔记(1) 怎么保存和使用训练好的参数和模型
- tensorflow: 保存和加载模型, 参数;以及使用预训练参数方法
- 利用numpy数组保存TensorFlow模型的参数