1.模型的保存
变量名称w1是在python内存中的,最后会被清楚,tensor的保留不会保留变量的名称,因此需要再对其进行name命名,和模型一起保存在index中,方面后面的调用
w1=tf.Variable(tf.compat.v1.random_normal(shape=[2]),name='w1')
import tensorflow as tf
tf.compat.v1.disable_eager_execution()
w1=tf.Variable(tf.compat.v1.random_normal(shape=[2]),name='example')# 生成标准的随机数,数量是2
w2=tf.Variable(tf.compat.v1.random_normal(shape=[5]),name='w2')
saver=tf.compat.v1.train.Saver() # 模型保存的类
sess=tf.compat.v1.Session()
sess.run(tf.compat.v1.global_variables_initializer())
saver.save(sess,'temp/model') # 保存模型
sess.close()
其中temp要提前建立文件夹,最后存储为model,共有四个文件
其中checkpoint是检查日志文件,model.data是所有的参数值,model.index保存变量的索引,model.meta保存计算图
调用
import tensorflow as tf
tf.compat.v1.disable_eager_execution()
sess= tf.compat.v1.Session()
saver=tf.compat.v1.train.import_meta_graph('temp/model.meta') # 导入保存好的计算图
saver.restore(sess,'temp/model') # 激活
w1_new=tf.compat.v1.get_default_graph().get_tensor_by_name('example:0')
# 获取计算图,通过名称获取tensor
# 标明是example的第1个,否则会报错
print(sess.run(w1_new))
sess.close()