tf.train.Saver()-tensorflow中模型的保存及讀取


作用:訓練網絡之后保存訓練好的模型,以及在程序中讀取已保存好的模型

使用步驟:

  • 實例化一個Saver對象 saver = tf.train.Saver() 
  • 在訓練過程中,定期調用saver.save方法,像文件夾中寫入包含當前模型中所有可訓練變量的checkpoint文件 saver.save(sess,FLAGG.train_dir,global_step=step) 
  • 之后可以使用saver.restore()方法,重載模型的參數,繼續訓練或者用於測試數據 saver.restore(sess,FLAGG.train_dir) 

在save之后會在相應的路徑下面新增如下四個紅色文件

在saver實例每次調用save方法時,都會創建三個數據文件和一個檢查點(checkpoint)文件,權重等參數被以字典的形式保存到.ckpt.data中,圖和元數據被保存到.ckpt.meta中,可以被tf.train.import_meta_graph加載到當前默認的圖

softmaxRegression.py

 1 # _*_ coding:utf-8 _*_
 2 import os
 3 os.environ['TF_CPP_MIN_LOG_LEVEL'] = '2'
 4 import tensorflow as tf
 5 from tensorflow.examples.tutorials.mnist import input_data
 6 
 7 #get the datase
 8 mnist = input_data.read_data_sets("MNIST_data/",one_hot=True)
 9 
10 print(mnist.train.images.shape,mnist.train.labels.shape)
11 
12 sess = tf.InteractiveSession()
13 
14 x = tf.placeholder(tf.float32,[None,784])
15 W = tf.Variable(tf.zeros([784,10]))
16 b = tf.Variable(tf.zeros([10]))
17 
18 y = tf.nn.softmax(tf.matmul(x,W)+b)
19 y_ = tf.placeholder(tf.float32,[None,10])
20 cross_entropy = tf.reduce_mean(-tf.reduce_sum(y_*tf.log(y),reduction_indices=[1]))
21 
22 train_step = tf.train.GradientDescentOptimizer(0.5).minimize(cross_entropy)
23 tf.global_variables_initializer().run()
24 
25 #保存模型對象saver
26 saver = tf.train.Saver()
27 
28 #判斷保存模型對象文件夾是否存在
29 if not os.path.exists('tmp/'):
30     print('i am here')
31     os.mkdir('tmp/')
32 else:
33     print("2")
34 
35 
36 if os.path.exists('tmp/chckpoint'):
37     saver.restore(sess,'tmp/model.ckpt')
38     correct_prediction = tf.equal(tf.arg_max(y, 1), tf.argmax(y_, 1))
39     accuracy = tf.reduce_mean(tf.cast(correct_prediction, tf.float32))
40     save_path = saver.save(sess, 'tmp/model.ckpt')
41     print("2")
42     print(accuracy.eval({x: mnist.test.images, y_: mnist.test.labels}))
43 else:
44     for i in range(1000):
45         batch_xs,batch_ys = mnist.train.next_batch(100)
46         train_step.run({x:batch_xs,y_:batch_ys})
47     correct_prediction = tf.equal(tf.arg_max(y,1),tf.argmax(y_,1))
48     accuracy = tf.reduce_mean(tf.cast(correct_prediction,tf.float32))
49     save_path = saver.save(sess,'tmp/model.ckpt')
50     print(accuracy.eval({x:mnist.test.images,y_:mnist.test.labels}))

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM