TensorFLow用Saver保存和恢复变量

yipeiwu_com6年前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 多维切片之冒号和三个点的用法介绍

初学python和numpy,对在学习多维切片的过程中遇到的问题做个总结。 一维切片就不说了,比较简单,先说下二维的,二维的理解了多维的就简单了。举个例子先建立一个5x5的二维数组 多...

用C++封装MySQL的API的教程

其实相信每个和mysql打过交道的程序员都应该会尝试去封装一套mysql的接口,这一次的封装已经记不清是我第几次了,但是每一次我希望都能做的比上次更好,更容易使用。 先来说一下这次的封装...

python发送邮件实例分享

python发送邮件实例分享

为了更好的理解邮件发送功能的实现,要先了解邮件发送系统的大致流程。首先  电子邮件之间的相互发送接受就像  邮局邮件发送一样,从一个站点(邮件发送服务器)到目的地站点...

Python双精度浮点数运算并分行显示操作示例

Python双精度浮点数运算并分行显示操作示例

本文实例讲述了Python双精度浮点数运算并分行显示操作。分享给大家供大家参考,具体如下: #coding=utf8 def doubleType(): ''''' Pyth...

python 实现Flask中返回图片流给前端展示

场景需求:需要在Flask服务器的本地找一张图片返回给前端展示出来。 问题疑点:通常前端的<img>标签只会接受url的形式来展示图片,没试过在返回服务器本地的一张图片给前端...