# tensorflow保存读取-【老鱼学tensorflow】

2018-03-01 07:50:47来源:cnblogs.com作者:dreampursuer人点击

# 保存模型的权重和偏置值

``import tensorflow as tf# 保存到文件W = tf.Variable([[1, 2, 3], [3, 4, 5]], dtype=tf.float32, name='weights')b = tf.Variable([[1, 2, 3]], dtype=tf.float32, name='biases')``

``init = tf.global_variables_initializer()sess = tf.Session()sess.run(init)``

``# 创建saversaver = tf.train.Saver()save_path = saver.save(sess, "D:/todel/python/saver/save_net.ckpt")print("保存的路径为：", save_path)``

``保存的路径为： D:/todel/python/saver/save_net.ckpt``

``import tensorflow as tf# 保存到文件W = tf.Variable([[1, 2, 3], [3, 4, 5]], dtype=tf.float32, name='weights')b = tf.Variable([[1, 2, 3]], dtype=tf.float32, name='biases')init = tf.global_variables_initializer()sess = tf.Session()sess.run(init)# 创建saversaver = tf.train.Saver()save_path = saver.save(sess, "D:/todel/python/saver/save_net.ckpt")print("保存的路径为：", save_path)``

# 恢复模型的权重和偏置值

``import tensorflow as tfimport numpy as np# 定义权重和偏置值的结构，但其中的数值随便填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")``

``saver = tf.train.Saver()sess = tf.Session()# 不需要对变量进行初始化，因为这些变量的值我们会从saver中进行恢复saver.restore(sess, "D:/todel/python/saver/save_net.ckpt")print("weights:", sess.run(W))print("biases:", sess.run(b))``

``weights: [[ 1.  2.  3.] [ 3.  4.  5.]]biases: [[ 1.  2.  3.]]``

``import tensorflow as tfimport numpy as np# 定义权重和偏置值的结构，但其中的数值随便填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")saver = tf.train.Saver()sess = tf.Session()# 不需要对变量进行初始化，因为这些变量的值我们会从saver中进行恢复saver.restore(sess, "D:/todel/python/saver/save_net.ckpt")print("weights:", sess.run(W))print("biases:", sess.run(b))``