TensorFlow模型保存和提取方法


一、TensorFlow模型保存和提取方法

1. TensorFlow通過tf.train.Saver類實現神經網絡模型的保存和提取。tf.train.Saver對象saver的save方法將TensorFlow模型保存到指定路徑中,saver.save(sess,"Model/model.ckpt"),實際在這個文件目錄下會生成4個人文件:

checkpoint文件保存了一個錄下多有的模型文件列表,model.ckpt.meta保存了TensorFlow計算圖的結構信息,model.ckpt保存每個變量的取值,此處文件名的寫入方式會因不同參數的設置而不同,但加載restore時的文件路徑名是以checkpoint文件中的“model_checkpoint_path”值決定的。

2. 加載這個已保存的TensorFlow模型的方法是saver.restore(sess,"./Model/model.ckpt"),加載模型的代碼中也要定義TensorFlow計算圖上的所有運算並聲明一個tf.train.Saver類,不同的是加載模型時不需要進行變量的初始化,而是將變量的取值通過保存的模型加載進來,注意加載路徑的寫法。若不希望重復定義計算圖上的運算,可直接加載已經持久化的圖,saver =tf.train.import_meta_graph("Model/model.ckpt.meta")

3.tf.train.Saver類也支持在保存和加載時給變量重命名,聲明Saver類對象的時候使用一個字典dict重命名變量即可,{"已保存的變量的名稱name": 重命名變量名},saver = tf.train.Saver({"v1":u1, "v2": u2})即原來名稱name為v1的變量現在加載到變量u1(名稱name為other-v1)中。

4. 上一條做的目的之一就是方便使用變量的滑動平均值。如果在加載模型時直接將影子變量映射到變量自身,則在使用訓練好的模型時就不需要再調用函數來獲取變量的滑動平均值了。載入時,聲明Saver類對象時通過一個字典將滑動平均值直接加載到新的變量中,saver = tf.train.Saver({"v/ExponentialMovingAverage": v}),另通過tf.train.ExponentialMovingAverage的variables_to_restore()函數獲取變量重命名字典。

此外,通過convert_variables_to_constants函數將計算圖中的變量及其取值通過常量的方式保存於一個文件中。

二、TensorFlow程序實現

[python]  view plain  copy
 
  1. # 本文件程序為配合教材及學習進度漸進進行,請按照注釋分段執行  
  2. # 執行時要注意IDE的當前工作過路徑,最好每段重啟控制器一次,輸出結果更准確  
  3.   
  4.   
  5. # Part1: 通過tf.train.Saver類實現保存和載入神經網絡模型  
  6.   
  7. # 執行本段程序時注意當前的工作路徑  
  8. import tensorflow as tf  
  9.   
  10. v1 = tf.Variable(tf.constant(1.0, shape=[1]), name="v1")  
  11. v2 = tf.Variable(tf.constant(2.0, shape=[1]), name="v2")  
  12. result = v1 + v2  
  13.   
  14. saver = tf.train.Saver()  
  15.   
  16. with tf.Session() as sess:  
  17.     sess.run(tf.global_variables_initializer())  
  18.     saver.save(sess, "Model/model.ckpt")  
  19.   
  20.   
  21. # Part2: 加載TensorFlow模型的方法  
  22.   
  23. import tensorflow as tf  
  24.   
  25. v1 = tf.Variable(tf.constant(1.0, shape=[1]), name="v1")  
  26. v2 = tf.Variable(tf.constant(2.0, shape=[1]), name="v2")  
  27. result = v1 + v2  
  28.   
  29. saver = tf.train.Saver()  
  30.   
  31. with tf.Session() as sess:  
  32.     saver.restore(sess, "./Model/model.ckpt"# 注意此處路徑前添加"./"  
  33.     print(sess.run(result)) # [ 3.]  
  34.   
  35.   
  36. # Part3: 若不希望重復定義計算圖上的運算,可直接加載已經持久化的圖  
  37.   
  38. import tensorflow as tf  
  39.   
  40. saver = tf.train.import_meta_graph("Model/model.ckpt.meta")  
  41.   
  42. with tf.Session() as sess:  
  43.     saver.restore(sess, "./Model/model.ckpt"# 注意路徑寫法  
  44.     print(sess.run(tf.get_default_graph().get_tensor_by_name("add:0"))) # [ 3.]  
  45.   
  46.   
  47. # Part4: tf.train.Saver類也支持在保存和加載時給變量重命名  
  48.   
  49. import tensorflow as tf  
  50.   
  51. # 聲明的變量名稱name與已保存的模型中的變量名稱name不一致  
  52. u1 = tf.Variable(tf.constant(1.0, shape=[1]), name="other-v1")  
  53. u2 = tf.Variable(tf.constant(2.0, shape=[1]), name="other-v2")  
  54. result = u1 + u2  
  55.   
  56. # 若直接生命Saver類對象,會報錯變量找不到  
  57. # 使用一個字典dict重命名變量即可,{"已保存的變量的名稱name": 重命名變量名}  
  58. # 原來名稱name為v1的變量現在加載到變量u1(名稱name為other-v1)中  
  59. saver = tf.train.Saver({"v1": u1, "v2": u2})  
  60.   
  61. with tf.Session() as sess:  
  62.     saver.restore(sess, "./Model/model.ckpt")  
  63.     print(sess.run(result)) # [ 3.]  
  64.   
  65.   
  66. # Part5: 保存滑動平均模型  
  67.   
  68. import tensorflow as tf  
  69.   
  70. v = tf.Variable(0, dtype=tf.float32, name="v")  
  71. for variables in tf.global_variables():  
  72.     print(variables.name) # v:0  
  73.   
  74. ema = tf.train.ExponentialMovingAverage(0.99)  
  75. maintain_averages_op = ema.apply(tf.global_variables())  
  76. for variables in tf.global_variables():  
  77.     print(variables.name) # v:0  
  78.                           # v/ExponentialMovingAverage:0  
  79.   
  80. saver = tf.train.Saver()  
  81.   
  82. with tf.Session() as sess:  
  83.     sess.run(tf.global_variables_initializer())  
  84.     sess.run(tf.assign(v, 10))  
  85.     sess.run(maintain_averages_op)  
  86.     saver.save(sess, "Model/model_ema.ckpt")  
  87.     print(sess.run([v, ema.average(v)])) # [10.0, 0.099999905]  
  88.   
  89.   
  90. # Part6: 通過變量重命名直接讀取變量的滑動平均值  
  91.   
  92. import tensorflow as tf  
  93.   
  94. v = tf.Variable(0, dtype=tf.float32, name="v")  
  95. saver = tf.train.Saver({"v/ExponentialMovingAverage": v})  
  96.   
  97. with tf.Session() as sess:  
  98.     saver.restore(sess, "./Model/model_ema.ckpt")  
  99.     print(sess.run(v)) # 0.0999999  
  100.   
  101.   
  102. # Part7: 通過tf.train.ExponentialMovingAverage的variables_to_restore()函數獲取變量重命名字典  
  103.   
  104. import tensorflow as tf  
  105.   
  106. v = tf.Variable(0, dtype=tf.float32, name="v")  
  107. # 注意此處的變量名稱name一定要與已保存的變量名稱一致  
  108. ema = tf.train.ExponentialMovingAverage(0.99)  
  109. print(ema.variables_to_restore())  
  110. # {'v/ExponentialMovingAverage': <tf.Variable 'v:0' shape=() dtype=float32_ref>}  
  111. # 此處的v取自上面變量v的名稱name="v"  
  112.   
  113. saver = tf.train.Saver(ema.variables_to_restore())  
  114.   
  115. with tf.Session() as sess:  
  116.     saver.restore(sess, "./Model/model_ema.ckpt")  
  117.     print(sess.run(v)) # 0.0999999  
  118.   
  119.   
  120. # Part8: 通過convert_variables_to_constants函數將計算圖中的變量及其取值通過常量的方式保存於一個文件中  
  121.   
  122. import tensorflow as tf  
  123. from tensorflow.python.framework import graph_util  
  124.   
  125. v1 = tf.Variable(tf.constant(1.0, shape=[1]), name="v1")  
  126. v2 = tf.Variable(tf.constant(2.0, shape=[1]), name="v2")  
  127. result = v1 + v2  
  128.   
  129. with tf.Session() as sess:  
  130.     sess.run(tf.global_variables_initializer())  
  131.     # 導出當前計算圖的GraphDef部分,即從輸入層到輸出層的計算過程部分  
  132.     graph_def = tf.get_default_graph().as_graph_def()  
  133.     output_graph_def = graph_util.convert_variables_to_constants(sess,  
  134.                                                         graph_def, ['add'])  
  135.   
  136.     with tf.gfile.GFile("Model/combined_model.pb"'wb') as f:  
  137.         f.write(output_graph_def.SerializeToString())  
  138.   
  139.   
  140. # Part9: 載入包含變量及其取值的模型  
  141.   
  142. import tensorflow as tf  
  143. from tensorflow.python.platform import gfile  
  144.   
  145. with tf.Session() as sess:  
  146.     model_filename = "Model/combined_model.pb"  
  147.     with gfile.FastGFile(model_filename, 'rb') as f:  
  148.         graph_def = tf.GraphDef()  
  149.         graph_def.ParseFromString(f.read())  
  150.   
  151.     result = tf.import_graph_def(graph_def, return_elements=["add:0"])  
  152.     print(sess.run(result)) # [array([ 3.], dtype=float32)]  


免責聲明!

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



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