133、TensorFlow加载模型(二)

# 选择哪个变量来保存和恢复
# 如果你没有传递任何的参数到tf.train.Saver()
# 这个saver会处理计算图中所有的变量
# 每一个变量都被保存,保存的名字就是当初创建他们时候的名字
# 有时候在checkpoint文件中声明名字也是很有用的
# 例如 你或许已经训练完一个模型,其中还有变量叫做weights
# 他的值你想存进文件中叫做params
# 有时候只保存和恢复模型子图中的变量也是有用的
# 例如你或许想训练一个有5个隐藏层的神经网络,
# 但是现在你想训练一个有6个隐藏层的神经网络,并且想重用前五层的网络
# 你可以使用saver类来保存和重用前五层的权重
# 你可以很容易地来指定保存和恢复变量的名字,通过tf.train.Saver()构造方法,通过使用下面两个中的一个
# 1、一系列的变量(保存时会使用他们本身的名字)
# 2、一个Python字典,keys是使用时候的名字,值是保存时候的名字
# 持续保存和恢复
import tensorflow as tf
tf.reset_default_graph()
# 创建一些变量
v1 = tf.get_variable("v1", [3], initializer=tf.zeros_initializer)
v2 = tf.get_variable("v2", [5], initializer=tf.zeros_initializer)

# Add ops to save and restore only 'v2' using the name "v2"
saver = tf.train.Saver({"v2":v2})

# Use the saver object normally after that
with tf.Session() as sess:
    # 初始化v1 , 因为the saver 不会初始化v1
    v1.initializer.run()
    saver.restore(sess, "tmp/model.ckpt")
    
    print("v1:%s" % v1.eval())
    # 这里的v2会使用从模型文件中加载的v2
    print("v2:%s" % v2.eval())

下面是输出的结果:

2018-02-17 11:24:11.015461: I C:\tf_jenkins\workspace\rel-win\M\windows\PY\35\tensorflow\core\platform\cpu_feature_guard.cc:137] Your CPU supports instructions that this TensorFlow binary was not compiled to use: AVX AVX2
v1:[ 0.  0.  0.]
v2:[-1. -1. -1. -1. -1.]

 

posted @ 2018-02-17 11:25  香港胖仔  阅读(298)  评论(0编辑  收藏  举报