import tensorflow as tf
#save to file
#remember to define same dtype and shape when restore
#W = tf.Variable(tf.truncated_normal([2, 3]),dtype=tf.float32,name='weight')
#b = tf.Variable(tf.truncated_normal([3]),dtype=tf.float32,name='biases')#dtype不定义会报错
#
#init = tf.global_variables_initializer()
#
#saver = tf.train.Saver()
#
#with tf.Session() as sess:
# sess.run(init)
# #save sess 里所有的东西,格式注意.ckpt,可以是别的格式
# save_path = saver.save(sess,"mynet/savetest1.ckpt")
# print("save path:" , save_path)
#restore variable
#redefine same dtype and shape for you variables
W = tf.Variable(tf.truncated_normal([2, 3]),dtype = tf.float32,name = 'weight')
b = tf.Variable(tf.truncated_normal([3]),dtype = tf.float32,name = 'biases')
#not need intial
saver = tf.train.Saver()## define a saver for saving and restoring
with tf.Session() as sess:
saver.restore(sess,"mynet/savetest1.ckpt")
print("weight: ",sess.run(W))
print("biases: ",sess.run(b))
运行错误:
Key Conv/biases not found in checkpoint
Variable rnn/rnn/basic_lstm_cell/kernel already exists(同样的解决方法)
原因: 保存和加载 在前后进行,在前后两次定义了
W = tf.Variable(xxx,name=”weight”)
相当于 在TensorFlow 图的堆栈创建了两次 name = “weight” 的变量,第二个(第n个)的实际 name 会变成 “weight_1” (“weight_n-1”),之后我们在保存 checkpoint 中实际搜索的是 “weight_n-1” 这个变量 而不是 “weight” ,因此就会出错。
解决方案:
(1)在加载过程中,定义 name 相同的变量前面加 tf.reset_default_graph()
清除默认图的堆栈,并设置全局图为默认图