欢迎来到代码驿站!

Python代码

当前位置:首页 > 软件编程 > Python代码

TensorFlow Saver:保存和读取模型参数.ckpt实例

时间:2021-04-27 09:09:21|栏目:Python代码|点击:

在使用TensorFlow的过程中,保存模型参数变量是很重要的一个环节,既可以保证训练过程信息不丢失,也可以帮助我们在需要快速恢复或使用一个模型的时候,利用之前保存好的参数之间导入,可以节省大量的训练时间。本文通过最简单的例程教大家如何保存和读取.ckpt文件。

一、保存到文件

首先是导入必要的东西:

import tensorflow as tf
import numpy as np

随便写几个变量:

# Save to file
# remember to define the same dtype and shape when restore
W = tf.Variable([[1,2,3],[3,4,5]], dtype=tf.float32, name='weights')
b = tf.Variable([[1,2,3]], dtype=tf.float32, name='biases')
 
init= tf.initialize_all_variables()

定义一个saver,来存储我们的各种变量:

saver = tf.train.Saver()

保存的文件用.ckpt后缀:

with tf.Session() as sess:
  sess.run(init)
  save_path = saver.save(sess, "my_net/save_net.ckpt")
  print("Save to path: ", save_path)

上面我们就完成了保存操作。

接下来我们要把之前保存过的变量取出来。

二、取出之前保存的变量

这里要注意,取出时要先开辟一个容器来装,shape和type要和我们之前保存的.ckpt一样。

# restore variables
# redefine the same shape and same type for your variables
W = tf.Variable(np.arange(6).reshape((2, 3)), dtype=tf.float32, name="weights")
b = tf.Variable(np.arange(3).reshape((1, 3)), dtype=tf.float32, name="biases")

restore时,不需要进行init= tf.initialize_all_variables()操作。

利用saver提取文件:

saver = tf.train.Saver()
with tf.Session() as sess:
  saver.restore(sess, "my_net/save_net.ckpt")
  print("weights:", sess.run(W))
  print("biases:", sess.run(b))

结果:

上一篇:python写一个md5解密器示例

栏    目:Python代码

下一篇:python中比较两个列表的实例方法

本文标题:TensorFlow Saver:保存和读取模型参数.ckpt实例

本文地址:http://www.codeinn.net/misctech/109878.html

推荐教程

广告投放 | 联系我们 | 版权申明

重要申明:本站所有的文章、图片、评论等,均由网友发表或上传并维护或收集自网络,属个人行为,与本站立场无关。

如果侵犯了您的权利,请与我们联系,我们将在24小时内进行处理、任何非本站因素导致的法律后果,本站均不负任何责任。

联系QQ:914707363 | 邮箱:codeinn#126.com(#换成@)

Copyright © 2020 代码驿站 版权所有