先上结论:如果tf.Variable要保存,一定要定义名字。
以保存两个二维数组为例子,看代码:
import tensorflow as tf
import numpy as np
w = tf.Variable([[11,12,13],[22,23,25]],dtype=tf.float32)
b = tf.Variable([[7,8,9],[1,2,3]],dtype=tf.float32)
init = tf.global_variables_initializer()
save = tf.train.Saver()
with tf.Session() as sess:
sess.run(init)
save_path = save.save(sess,“my_net/save_net.ckpt”)
print(“保存路径:”,save_path)
print(sess.run(w))
print(sess.run(b))
输出为:
保存路径: my_net/save_net.ckpt
[[11. 12. 13.]
[22. 23. 25.]]
[[7. 8. 9.]
[1. 2. 3.]]
提取数据代码:
import tensorflow as tf
import numpy as np
#先建立容器
b = tf.Variable(np.arange(6).reshape(2,3),dtype=tf.float32)
w = tf.Variable(np.arange(6).reshape(2,3),dtype=tf.float32)
#不需要初始化
save = tf.train.Saver()
with tf.Session() as sess:
#提取数据
save.restore(sess,“my_net/save_net.ckpt”)
print(“weights”,sess.run(w))
print(“biases”,sess.run(b))
输出为:
weights [[7. 8. 9.]
[1. 2. 3.]]
biases [[11. 12. 13.]
[22. 23. 25.]]
结论:如果保存的tf.Variable数组形状一样,则提取数据时,数据的内容与保存变量代码的变量声明顺讯和提取数据代码的变量申明顺序有关。
如果在保存变量和提取变量时,加个名字,则与顺序无关。
保存变量代码如下:
import tensorflow as tf
import numpy as np
w = tf.Variable([[11,12,13],[22,23,25]],dtype=tf.float32,name=“w”)
b = tf.Variable([[7,8,9],[1,2,3]],dtype=tf.float32,name=“b”)
init = tf.global_variables_initializer()
save = tf.train.Saver()
with tf.Session() as sess:
sess.run(init)
save_path = save.save(sess,“my_net/save_net.ckpt”)
print(“保存路径:”,save_path)
print(sess.run(w))
print(sess.run(b))
输出为:
保存路径: my_net/save_net.ckpt
[[11. 12. 13.]
[22. 23. 25.]]
[[7. 8. 9.]
[1. 2. 3.]]
提取变量代码如下:
import tensorflow as tf
import numpy as np
#先建立容器
b = tf.Variable(np.arange(6).reshape(2,3),dtype=tf.float32,name=“b”)
w = tf.Variable(np.arange(6).reshape(2,3),dtype=tf.float32,name=“w”)
#不需要初始化
save = tf.train.Saver()
with tf.Session() as sess:
#提取数据
save.restore(sess,“my_net/save_net.ckpt”)
print(“weights”,sess.run(w))
print(“biases”,sess.run(b))
输出为:
weights [[11. 12. 13.]
[22. 23. 25.]]
biases [[7. 8. 9.]
[1. 2. 3.]]
变量的值根据名字精确提取