TensorFlow 模型保存/载入

我们在上线使用一个算法模型的时候,首先必须将已经训练好的模型保存下来。tensorflow保存模型的方式与sklearn不太一样,sklearn很直接,一个sklearn.externals.joblib的dump与load方法就可以保存与载入使用。而tensorflow由于有graph, operation 这些概念,保存与载入模型稍显麻烦。由于TensorFlow 的版本一直在更新, 保存模型的方法也发生了改变,在python 环境,和在C++ 环境(移动端) 等不同的平台需要的模型文件也是不也一样的。

(https://stackoverflow.com/questions/44516609/tensorflow-what-is-the-relationship-between-ckpt-file-and-ckpt-meta-and-ckp有一个解释如下)

  • the .ckpt file is the old version output of saver.save(sess), which is the equivalent of your .ckpt-data (see below)

  • the "checkpoint" file is only here to tell some TF functions which is the latest checkpoint file.

  • .ckpt-meta contains the metagraph, i.e. the structure of your computation graph, without the values of the variables (basically what you can see in tensorboard/graph).

  • .ckpt-data contains the values for all the variables, without the structure. To restore a model in python, you'll usually use the meta and data files with (but you can also use the .pb file):

saver = tf.train.import_meta_graph(path_to_ckpt_meta)
saver.restore(sess, path_to_ckpt_data)
  • I don't know exactly for .ckpt-index, I guess it's some kind of index needed internally to map the two previous files correctly. Anyway it's not really necessary usually, you can restore a model with only .ckpt-meta and .ckpt-data.

  • the .pb file can save your whole graph (meta + data). To load and use (but not train) a graph in c++ you'll usually use it, created with freeze_graph, which creates the .pb file from the meta and data. Be careful, (at least in previous TF versions and for some people) the py function provided by freeze_graph did not work properly, so you'd have to use the script version. Tensorflow also provides a tf.train.Saver.to_proto() method, but I don't know what it does exactly.

一、基本方法

网上搜索tensorflow模型保存,搜到的大多是基本的方法。即

保存

  1. 定义变量
  2. 使用saver.save()方法保存

载入

  1. 定义变量
  2. 使用saver.restore()方法载入

如 保存 代码如下

import tensorflow as tf
import numpy as np W = tf.Variable([[1,1,1],[2,2,2]],dtype = tf.float32,name='w')
b = tf.Variable([[0,1,2]],dtype = tf.float32,name='b') init = tf.initialize_all_variables()
saver = tf.train.Saver()
with tf.Session() as sess:
sess.run(init)
save_path = saver.save(sess,"save/model.ckpt")

载入代码如下

import tensorflow as tf
import numpy as np W = tf.Variable(tf.truncated_normal(shape=(2,3)),dtype = tf.float32,name='w')
b = tf.Variable(tf.truncated_normal(shape=(1,3)),dtype = tf.float32,name='b') saver = tf.train.Saver()
with tf.Session() as sess:
saver.restore(sess,"save/model.ckpt")

二、不需重新定义网络结构的方法

tf.train.import_meta_graph(
meta_graph_or_file,
clear_devices=False,
import_scope=None,
**kwargs
)

这个方法可以从文件中将保存的graph的所有节点加载到当前的default graph中,并返回一个saver。也就是说,我们在保存的时候,除了将变量的值保存下来,其实还有将对应graph中的各种节点保存下来,所以模型的结构也同样被保存下来了。

比如我们想要保存计算最后预测结果的y,则应该在训练阶段将它添加到collection中。具体代码如下

保存

### 定义模型
input_x = tf.placeholder(tf.float32, shape=(None, in_dim), name='input_x')
input_y = tf.placeholder(tf.float32, shape=(None, out_dim), name='input_y') w1 = tf.Variable(tf.truncated_normal([in_dim, h1_dim], stddev=0.1), name='w1')
b1 = tf.Variable(tf.zeros([h1_dim]), name='b1')
w2 = tf.Variable(tf.zeros([h1_dim, out_dim]), name='w2')
b2 = tf.Variable(tf.zeros([out_dim]), name='b2')
keep_prob = tf.placeholder(tf.float32, name='keep_prob')
hidden1 = tf.nn.relu(tf.matmul(self.input_x, w1) + b1)
hidden1_drop = tf.nn.dropout(hidden1, self.keep_prob)
### 定义预测目标
y = tf.nn.softmax(tf.matmul(hidden1_drop, w2) + b2)
# 创建saver
saver = tf.train.Saver(...variables...)
# 假如需要保存y,以便在预测时使用
tf.add_to_collection('pred_network', y)
sess = tf.Session()
for step in xrange(1000000):
sess.run(train_op)
if step % 1000 == 0:
# 保存checkpoint, 同时也默认导出一个meta_graph
# graph名为'my-model-{global_step}.meta'.
saver.save(sess, 'my-model', global_step=step)

载入

with tf.Session() as sess:
new_saver = tf.train.import_meta_graph('my-save-dir/my-model-10000.meta')
new_saver.restore(sess, 'my-save-dir/my-model-10000')
# tf.get_collection() 返回一个list. 但是这里只要第一个参数即可
y = tf.get_collection('pred_network')[0] graph = tf.get_default_graph() # 因为y中有placeholder,所以sess.run(y)的时候还需要用实际待预测的样本以及相应的参数来填充这些placeholder,而这些需要通过graph的get_operation_by_name方法来获取。
input_x = graph.get_operation_by_name('input_x').outputs[0]
keep_prob = graph.get_operation_by_name('keep_prob').outputs[0] # 使用y进行预测
sess.run(y, feed_dict={input_x:...., keep_prob:1.0})

这里有两点需要注意的:

一、 saver.restore()时填的文件名,因为在saver.save的时候,每个checkpoint会保存三个文件,如 
my-model-10000.metamy-model-10000.indexmy-model-10000.data-00000-of-00001 
import_meta_graph时填的就是meta文件名,我们知道权值都保存在my-model-10000.data-00000-of-00001这个文件中,但是如果在restore方法中填这个文件名,就会报错,应该填的是前缀,这个前缀可以使用tf.train.latest_checkpoint(checkpoint_dir)这个方法获取。

二、模型的y中有用到placeholder,在sess.run()的时候肯定要feed对应的数据,因此还要根据具体placeholder的名字,从graph中使用get_operation_by_name方法获取。

tensorflow model save and restore的更多相关文章

  1. tensorflow的save和restore

    使用tensorflow中的save和restore可以对模型进行保存和恢复 import tensorflow as tf v1 = tf.Variable(tf.random_normal([1, ...

  2. canvas的save与restore方法的作用

    网上搜罗了一堆资料,最后总结一下. save:用来保存Canvas的状态.save之后,可以调用Canvas的平移.放缩.旋转.错切.裁剪等操作. restore:用来恢复Canvas之前保存的状态. ...

  3. canvas 图片拖拽旋转之二——canvas状态保存(save和restore)

    引言 在上一篇日志“canvas 图片拖拽旋转之一”中,对坐标转换有了比较深入的了解,但是仅仅利用坐标转换实现的拖拽旋转,会改变canvas坐标系的状态,从而影响画布上其他元素的绘制.因此,这个时候需 ...

  4. canvas中save()和restore()方法

    save()和restore()方法是绘制复杂图形不可缺少的方法它们是分别用来保存和恢复canvas状态的,都没有参数 save():用来保存Canvas的状态.save之后,可以调用Canvas的平 ...

  5. canvas 中save和restore的用法

    在创建新的控件或修改现有的控件时,我们都会涉及到重写控件或View的onDraw方法. onDraw方法会传入一个Canvas对象,它是你用来绘制控件视觉界面的画布. 在onDraw方法里,我们经常会 ...

  6. HTML5中canvas的save和restore方法

    canvas的save和restore方法: save() 方法把当前绘画状态的一份拷贝压入到一个保存图像状态的栈中.这里的绘画状态指坐标原点.变形时的变化矩阵(该矩阵是调用 rotate().sca ...

  7. HTM5 之 Canvas save 、restore 恢复画布状态的理解

    save是用来保存canvas状态,这句话很关键,意思是指后续对canvas的操作:平移.放缩.旋转.错切.裁剪等可以恢复. 我之前一直没能理解,认为对画布的画线等操作也可以恢复,其实不是这样子的,只 ...

  8. [js高手之路] html5 canvas系列教程 - 状态详解(save与restore)

    本文内容与路径([js高手之路] html5 canvas系列教程 - 开始路径beginPath与关闭路径closePath详解)是canvas中比较重要的概念.掌握理解他们是做出复杂canvas动 ...

  9. 学习笔记TF053:循环神经网络,TensorFlow Model Zoo,强化学习,深度森林,深度学习艺术

    循环神经网络.https://github.com/aymericdamien/TensorFlow-Examples/blob/master/examples/3_NeuralNetworks/re ...

随机推荐

  1. hdu 5064 满足b2−b1≤b3−b2... 的最长子序列

    http://acm.hdu.edu.cn/showproblem.php?pid=5064 要找出一个数组中满足b2−b1≤b3−b2≤⋯≤bt−bt−1 的最大的t 直接引题解: 1003 Fin ...

  2. hdu 4946 凸包注意重点

    http://acm.hdu.edu.cn/showproblem.php?pid=4946 给你n个点的坐标和速度,如果一个点能够到达无穷远处,且花费的时间是最少的,则此点输出1,否则输出0. 每个 ...

  3. 【最大流之Dinic算法】POJ1273 【 & 当前弧优化 & 】

    总评一句:Dinic算法的基本思想比较好理解,就是它的当前弧优化的思想,网上的资料也不多,所以对于当前弧的优化,我还是费了很大的功夫的,现在也一知半解,索性就写一篇博客,来发现自己哪里的算法思想还没理 ...

  4. Python学习-17.Python中的错误处理(二)

    错误是多种多样的,在 except 语句中,可以捕获指定的异常 修改代码如下: import io path = r'' mode = 'w' try: file = open(path,mode) ...

  5. DevOps Workshop 研发运维一体化(北京第二场) 2016.04.27

    北京不亏为首都,人才济济,对微软DevOps解决方案感兴趣的人太多.我们与微软公司临时决定再家一场培训. 我之前在博客中(DevOps Workshop 研发运维一体化第一场(微软亚太研发集团总部)h ...

  6. GitHub Android 开源项目汇总 (转)

    转自:http://blog.csdn.net/ithomer/article/details/8882236 GitHub 上的开源项目不胜枚举,越来越多的开源项目正在迁移到GitHub平台上.基于 ...

  7. asp.net—执行分页存储过程的函数

    分页存储过程的T—SQL在之前的文章中已经跟大家分享过了 现在就对应 分页存储过程 跟大家分享下在.net中执行的函数. 该文章是希望给予新手一些编程过程中的帮助(大神可以帮忙指出代码中的不妥之处) ...

  8. netcore问题总结

    1. webclient在在netcore异步文件下载的时候,下载进度为空,只有最后下载完了,进度才会是100%,但是在netframework中就没有这个问题,异步文件下载进度会正常提醒. 2. n ...

  9. WPF 获取表格里面的内容

    DataRowView dataRow = DataGridCase.SelectedItem as DataRowView; 代码转为数组分别获取.

  10. Day4 作业

    a=[1,2,3,6,"dfs",100]s=a[-1:]print (s)答案:[100] s=a[-1:0:-1]print(s) 答案:[100, 'dfs', 6, 3, ...