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设计】。

相关文章

在pyqt5中QLineEdit里面的内容回车发送的实例

在PyQt5中QLineEdit里面的内容回车发送的方法是和PyQt4中不同的,主要是信号槽的写法的改变导致的。 具体不同如下: 在PyQt4中,我们要进行回车发送的时候,一般这么写:...

pytorch查看torch.Tensor和model是否在CUDA上的实例

pytorch查看torch.Tensor和model是否在CUDA上的实例

今天训练faster R-CNN时,发现之前跑的很好的程序(是指在运行程序过程中,显卡利用率能够一直维持在70%以上),今天看的时候,显卡利用率很低,所以在想是不是我的训练数据torch...

python实现月食效果实例代码

python实现月食效果实例代码

我们在学习Python当中的pygame模块时,我们都知道我们可以通过使用 pygame模块实现很多功能性的东西,但是很多人应该不知道怎么通过使用pygame实现月食的效果吧,接下来我就...

Python基于Tensor FLow的图像处理操作详解

Python基于Tensor FLow的图像处理操作详解

本文实例讲述了Python基于Tensor FLow的图像处理操作。分享给大家供大家参考,具体如下: 在对图像进行深度学习时,有时可能图片的数量不足,或者希望网络进行更多的学习,这时可以...

Python中文编码那些事

首先,要明白encode()和decode()的区别  encode()的作用是将Unicode编码的字符串转换为其他编码格式。 例如: st1.encode("utf-8")...