TensorFLow用Saver保存和恢复变量

yipeiwu_com5年前Python基础

本文为大家分享了TensorFLow用Saver保存和恢复变量的具体代码,供大家参考,具体内容如下

建立文件tensor_save.py, 保存变量v1,v2的tensor到checkpoint files中,名称分别设置为v3,v4。

import tensorflow as tf

# Create some variables.
v1 = tf.Variable(3, name="v1")
v2 = tf.Variable(4, name="v2")

# Create model
y=tf.add(v1,v2)

# Add an op to initialize the variables.
init_op = tf.initialize_all_variables()

# Add ops to save and restore all the variables.
saver = tf.train.Saver({'v3':v1,'v4':v2})

# Later, launch the model, initialize the variables, do some work, save the
# variables to disk.
with tf.Session() as sess:
 sess.run(init_op)
 print("v1 = ", v1.eval())
 print("v2 = ", v2.eval())
 # Save the variables to disk.
 save_path = saver.save(sess, "f:/tmp/model.ckpt")
 print ("Model saved in file: ", save_path)

建立文件tensor_restror.py, 将checkpoint files中名称分别为v3,v4的tensor分别恢复到变量v3,v4中。

import tensorflow as tf

# Create some variables.
v3 = tf.Variable(0, name="v3")
v4 = tf.Variable(0, name="v4")

# Create model
y=tf.mul(v3,v4)

# Add ops to save and restore all the variables.
saver = tf.train.Saver()

# Later, launch the model, use the saver to restore variables from disk, and
# do some work with the model.
with tf.Session() as sess:
 # Restore variables from disk.
 saver.restore(sess, "f:/tmp/model.ckpt")
 print ("Model restored.")
 print ("v3 = ", v3.eval())
 print ("v4 = ", v4.eval())
 print ("y = ",sess.run(y))

以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持【听图阁-专注于Python设计】。

相关文章

Python实现两款计算器功能示例

本文实例为大家分享了Python实现计算器功能示例代码,供大家参考,具体内容如下 1.简单计算器 #计算一个表达式的时候,首先肯定是先算括号里面的,再算乘除法,后算加减法 imp...

python用win32gui遍历窗口并设置窗口位置的方法

最近电脑打开某个软件却看不见窗口,在任务栏上看到软件明明已经运行,猜想一定是什么原因造成软件窗口位置偏离屏幕的有效坐标太远。尝试重启电脑,重装软件,都没有解决,看来是在注册表存储了位置信...

pandas数据处理基础之筛选指定行或者指定列的数据

pandas数据处理基础之筛选指定行或者指定列的数据

pandas主要的两个数据结构是:series(相当于一行或一列数据机构)和DataFrame(相当于多行多列的一个表格数据机构)。 本文为了方便理解会与excel或者sql操作行或列来...

Python Numpy 实现交换两行和两列的方法

numpy应该是一个和常用的包了,但是在百度查了很久,也没有查到如何交换两列(交换两行的有),所以查看了其他的文档,找到了方法。 交换两行 比如a = np.array([[1,2,3]...

PyMongo安装使用笔记

这里是简单的安装和使用记录,首先要有一个可用的mongo环境,win环境或者linux环境都可以。 假定你对mongo有所了解和知道一些命令行操作。 安装和更新 跟大多数py包安装一样,...