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

相关文章

Python3 Tkinter选择路径功能的实现方法

Python3 Tkinter选择路径功能的实现方法

效果基于Python3。 在自己写小工具的时候因为这个功能纠结了一会儿,这里写个小例子,供有需要的参考。 小例子,就是点击按钮打开路径选择窗口,选择后把值传给Entry输出。 效果预览...

python中文分词,使用结巴分词对python进行分词(实例讲解)

python中文分词,使用结巴分词对python进行分词(实例讲解)

在采集美女站时,需要对关键词进行分词,最终采用的是python的结巴分词方法。 中文分词是中文文本处理的一个基础性工作,结巴分词利用进行中文分词。 其基本实现原理有三点: 1.基于Tri...

对python中url参数编码与解码的实例详解

一、简介 在python中url,对于中文等非ascii码字符,需要进行参数的编码与解码。 二、关键代码 1、url编码 对字符串编码用urllib.parse包下的quote(stri...

在vscode中配置python环境过程解析

在vscode中配置python环境过程解析

1.安装vscode和python3.7(安装路径在:E:\Python\Python37); 2.打开vscode,在左下角点击设置图标选择setting,搜索python path,...

简单谈谈Python流程控制语句

人们常说人生就是一个不断做选择题的过程:有的人没得选,只有一条路能走;有的人好一点,可以二选一;有些能力好或者家境好的人,可以有更多的选择;还有一些人在人生的迷茫期会在原地打转,找不到方...