zoukankan      html  css  js  c++  java
  • TensorFlow模型保存和提取方法

    TensorFlow模型保存和提取方法

    原创 2017年06月01日 11:25:25

    一、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)]  
  • 相关阅读:
    .htaccess
    windows快速搭建wamp环境,多站点域名访问
    require与include的区别
    PHP常用操作的字符串函数
    高效做事的习惯
    成功?!
    面向对象程序设计
    失落 绝望
    jquery学习收获
    XML操作类
  • 原文地址:https://www.cnblogs.com/developer-ios/p/7855444.html
Copyright © 2011-2022 走看看