"""
#存储
import tensorflow as tf
#重构计算图,注意计算图和变量取值分开看,计算图是结构而值是计算图中变量具体的取值
a=tf.Variable(tf.constant(1),name="v1") #在checkpoint文件中的名字为v1
b=tf.Variable(tf.constant(1),name="v2")
saver=tf.train.Saver()
result=a+b
ini_op=tf.initialize_all_variables()
with tf.Session() as sess:
sess.run(ini_op)
saver.save(sess,"/model/model.ckpt")
"""
"""
#同名字恢复
import tensorflow as tf
m=tf.Variable(tf.constant(1),name="v1") #name参数与存储的名字一样
n=tf.Variable(tf.constant(1),name="v2")
saver=tf.train.Saver([m,n]) #取与m,n变量name对应存储的变量值,也可以传入[m]表示只取m
result=m+n
with tf.Session() as sess:
saver.restore(sess,"/model/model.ckpt") #运行成功说明在checkpoint记录的是变量name
"""
"""
#重命名实现
import tensorflow as tf
a=tf.Variable(tf.constant(1),name="model_1") #name参数与存储的名字不一样
b=tf.Variable(tf.constant(1),name="model_2")
saver=tf.train.Saver({"v1":a,"v2":b}) #传入字典,如果参数为空,那么tensroflow默认传入key值为上诉的变量对象组成的列表
result=a+b
with tf.Session() as sess:
saver.restore(sess,"/model/model.ckpt")
"""
"""
#上诉的重命名变量可以很方便的应用到前向传播中,我们可以读取训练好的
#模型的影子变量传入前向传播函数里得到预测值,下面创建保存滑动平均模型的样例
import tensorflow as tf
v=tf.Variable(0,name='v',dtype=tf.float32)
mean_class=tf.train.ExponentialMovingAverage(0.99)
mean_op=mean_class.apply(tf.all_variables())
saver=tf.train.Saver()
with tf.Session() as sess:
tf.initialize_all_variables().run()
sess.run(tf.assign(v,10))
sess.run(mean_op)
saver.save(sess,"D:/model/model.ckpt")
"""
#恢复滑动平均模型
import tensorflow as tf
v=tf.Variable(0,dtype=tf.float32,name="v")
mean_class=tf.train.ExponentialMovingAverage(0.99)
saver=tf.train.Saver(mean_class.variables_to_restore()) #默认所有可训练变量和有影子变量的变量
#If an ExponentialMovingAverage object is created and the apply() method is
#called on a list of variables, these variables will be added to the
#GraphKeys.MOVING_AVERAGE_VARIABLES collection.
with tf.Session() as sess:
saver.restore(sess,"D:/model/model.ckpt")
print(sess.run(v))