import tensorflow as tf
import numpy as np
# save to file#remember to define the same dtype and shape when restore
W=tf.Variable([[1,2,3],[4,5,6]], dtype=tf.float32, name='Weights')# 最好给个dtype
b=tf.Variable([[1,2,3]], dtype=tf.float32, name='biases')
init=tf.global_variables_initializer()
saver=tf.train.Saver()# 用saver存储各种变量with tf.Session()as sess:
sess.run(init)
save_path=saver.save(sess,'D:/try/save.ckpt')# 保存之后会返回一个值,返回的值存在save_path中,restore时会换成saver.restore# 以ckpt的格式保存print('save to path:', save_path)#restore variables#redefine the same shape and same type for your variables
tf.reset_default_graph()#保存和加载两次定义了W和b,用该语句清除默认图的堆栈,并设置全局图为默认图
W=tf.Variable(np.arange(6).reshape((2,3)),dtype=tf.float32,name='Weights')
b=tf.Variable(np.arange(3).reshape((1,3)),dtype=tf.float32,name='biases')#not need init step
saver=tf.train.Saver()with tf.Session()as sess:
saver.restore(sess,'D:/try/save.ckpt')print('Weight:',sess.run(W))print('biases:',sess.run(b))