<jupyter_start><jupyter_text>加载变量并重命名的使用场景：在滑动平均模型中，加载模型时直接将影子变量映射到变量自身，那么在使用训练好的模型时就不需要再调用函数来获取变量的滑动平均值，样例如下：<jupyter_code>import tensorflow as tf

v=tf.Variable(0,dtype=tf.float32,name='v')

for variables in tf.global_variables():
    print variables.name
    """
    v:0
    """
    
ema=tf.train.ExponentialMovingAverage(0.99)
maintain_averages_op=ema.apply(tf.global_variables())
#声明滑动平均模型之后，Tensorflow会自动生成一个影子变量
for variables in tf.global_variables():
    print variables.name
    """
    v:0
    v:0
    v/ExponentialMovingAverage:0
    """
    
saver=tf.train.Saver()
with tf.Session() as sess:
    sess.run(tf.global_variables_initializer())
    
    sess.run(tf.assign(v,10))
    sess.run(maintain_averages_op)
    saver.save(sess,'./tmp/variable_rename/model.ckpt')
    """
    v:0   v/ExponentialMovingAverage:0
    这两个变量都会保存下来
    """
    print sess.run([v,ema.average(v)])
    
import tensorflow as tf

v=tf.Variable(0,dtype=tf.float32,name='v')

#通过变量重命名将原来的v的滑动平均值赋值给v
saver=tf.train.Saver({'v/ExponentialMovingAverage':v})
with tf.Session() as sess:
    saver.restore(sess,'./tmp/variable_rename/model.ckpt')
    print sess.run(v)#输出值便是滑动平均值
    
#加载滑动平均值的一种便捷方法
import tensorflow as tf

v=tf.Variable(0,dtype=tf.float32,name='v')
ema=tf.train.ExponentialMovingAverage(0.99)

#此函数可以直接生成重命名所需要的字典
print ema.variables_to_restore()

saver=tf.train.Saver(ema.variables_to_restore())

with tf.Session() as sess:
    saver.restore(sess,'./tmp/variable_rename/model.ckpt')
    print sess.run(v)<jupyter_output>{u'v/ExponentialMovingAverage': <tf.Variable 'v:0' shape=() dtype=float32_ref>}
INFO:tensorflow:Restoring parameters from ./tmp/variable_rename/model.ckpt
0.0999999<jupyter_text>convert_variables_to_constants运用场景 tf.train.Saver()会保存全部信息；而在测试、离线预测或者迁移学习的时候，只需要知道如何从神经网络的输入层经过向前传播计算得到输出成即可。 利用convert_variables_to_constants方法可以将Tensorflow计算图统一存放在一个文件中，这样也更方便。样例如下：<jupyter_code>#存储
import tensorflow as tf
from tensorflow.python.framework import graph_util

v1=tf.Variable(tf.constant(1.0,shape=[1]),name='v1')
v2=tf.Variable(tf.constant(2.0,shape=[1]),name='v2')

result=v1+v2

with tf.Session() as sess:
    sess.run(tf.global_variables_initializer())
    graph_def=tf.get_default_graph().as_graph_def()
    
    out_graph_def=graph_util.convert_variables_to_constants(
        sess,
        graph_def,
        ['add']
    )
    
    with tf.gfile.GFile('./tmp/convert_vtoc/model.pd','wb') as f:
        f.write(out_graph_def.SerializeToString())
    
#读取
import tensorflow as tf
from tensorflow.python.platform import gfile

with tf.Session() as sess:
    model_filename='./tmp/convert_vtoc/model.pd'
    with gfile.FastGFile(model_filename,'rb') as f:
        graph_def=tf.GraphDef()
        graph_def.ParseFromString(f.read())
        
    result=tf.import_graph_def(graph_def,return_elements=['add:0'])
    print sess.run(result)
#持久化原理与数据格式
import tensorflow as tf

v1=tf.Variable(tf.constant(1.0,shape=[1]),name='v1')
v2=tf.Variable(tf.constant(1.0,shape=[1]),name='v2')
result=v1+v2

saver=tf.train.Saver()
saver.export_meta_graph('./tmp/meta_data/model.ckpt.meta.json',as_text=True)<jupyter_output><empty_output>
{'fraction_non_alphanumeric': 0.13944603629417382, 'fraction_numerical': 0.01878382680674944, 'mean_word_length': 5.1607843137254905, 'pattern_counts': {'":': 0, '<': 9, '<?xml version=': 0, '>': 9, 'https://': 0, 'lorem ipsum': 0, 'www.': 0, 'xml': 0}, 'pii_count': 0, 'substrings_counts': 0, 'word_list_counts': {'cursed_substrings.json': 0, 'profanity_word_list.json': 0, 'sexual_word_list.json': 0, 'zh_pornsignals.json': 0}}
{'chain_length': '2', 'dir': 'jupyter-structured-clean-dedup', 'id': '213562', 'license': 'MIT', 'n_tokens_mistral': 1393, 'n_tokens_neox': 1430, 'n_words': 140, 'path': 'notebooks/tensorflow_5.4_model_saver.ipynb', 'repo_name': 'shiyeli/jupyter_notebook', 'size': '3141'}