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

相关文章

解决Django生产环境无法加载静态文件问题的解决

起步 线上部署时因设置了 settings.DEBUG = False 会导致静态文件都是 404 的情况。主要原因是应为关闭DEBUG模式后,Django 便不提供静态文件服务了。...

Python加载带有注释的Json文件实例

由于json文件不支持注释,所以如果在json文件中标记了注释,则使用python中的json.dump()无法加载该json文件。 本文旨在解决当定义“//”为json注释时,如何正确...

Python操作mysql数据库实现增删查改功能的方法

本文实例讲述了Python操作mysql数据库实现增删查改功能的方法。分享给大家供大家参考,具体如下: #coding=utf-8 import MySQLdb class Mysq...

pygame 精灵的行走及二段跳的实现方法(必看篇)

pygame 精灵的行走及二段跳的实现方法(必看篇)

不得不承认《Python游戏编程入门》这本书翻译、排版非常之烂,但是里面的demo还是很好的,之前做了些改编放到这里。 先是素材: 背景 精灵 所有素材均取自此书 接下来就是精灵类的...

Python socket套接字实现C/S模式远程命令执行功能案例

本文实例讲述了Python socket套接字实现C/S模式远程命令执行功能。分享给大家供大家参考,具体如下: 一. 前言 要求: 使用python的socket套接字编写服务器/客户...