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方法获取。

转载于:https://www.cnblogs.com/zongfa/p/9153437.html

tensorflow model save and restore相关推荐

  1. A quick complete tutorial to save and restore Tensorflow models

    In this Tensorflow tutorial, I shall explain: How does a Tensorflow model look like? How to save a T ...

  2. Tensorflow: 保存和复原模型(save and restore)

    报错: is not valid checkpoint 解决: module_file = tf.train.latest_checkpoint(diag_obj.save_path) saver.r ...

  3. keras/tensorflow 模型保存后重新加载准确率为0 model.save and load giving different result

    我在用别人的代码跑程序的时候遇到了这个问题: keras 模型保存后重新加载准确率为0 GitHub上有个issue:model.save and load giving different resu ...

  4. 同样是保存模型,model.save()和model. save_weights ()有何区别

    model.save()保存了模型的图结构和模型的参数,保存模型的后缀是.hdf5. model. save_weights ()只保存了模型的参数,并没有保存模型的图结构,保存模型的后缀使用.h5. ...

  5. 理解Canvas的save()和restore()方法

    save()和restore()方法是绘制复杂图形必不可少的方法.它们分别是用来保存和恢复 canvas 状态的,都没有参数. Canvas 状态是以堆(stack)的方式保存的,每一次调用 save ...

  6. Canvas的save和restore方法

    2019独角兽企业重金招聘Python工程师标准>>> Canvas里的两个重要方法,一直很疑惑. save和restore方法是成对出现的,但是restore必然对应一个save方 ...

  7. Android画布的保存,Android canvas用法介绍之save()和restore()

    一. 首先讲一下canvas的save 和 restore功能. 这是canvas很有魅力的一个部分. onDraw方法会传入一个Canvas对象,它是你用来绘制控件视觉界面的画布. 在onDraw方 ...

  8. Canvas的save和restore

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

  9. canvas像素操作、save与restore、合成与变形

    一.canvas像素操作 (1)获取图像像素 (2)写入像素数据 (3)创建像素数据 (4)小案例,将canvasA画布的图像复制到canvasB中 二.canvas的save与restore 三.c ...

最新文章

  1. 不可错过的2019秋招CV岗心得!原来拿offer也是有套路的
  2. Day8 - Python网络编程 Socket编程 --转自金角大王
  3. Cluster table import - BSP UI component source code is actually stored in cluster table
  4. 二叉树题目----2 检查两颗树是否相同 和 对称二叉树的判定
  5. html边框大一点,CSS3 框大小(box-sizing)
  6. pve 加大local容量_proxmox ve (PVE) 增加 local 目录的大小即扩容
  7. cpu高 load 高 内存高 io 高怎么排查
  8. (数据科学学习手札05)Python与R数据读入存出方式的总结与比较
  9. android中进行https连接的方式的详解
  10. 181226每日一句
  11. MASM5.0下载安装与运行第一个HelloWorld
  12. 人工神经网络翻译的优点,神经网络机器翻译技术
  13. 《成为乔布斯》读后感
  14. Win300英雄服务器不显示,win10系统玩不了300英雄的还原步骤
  15. Python猜数字项目源代码
  16. 零基础入门,资深吃货带你搞懂大数据
  17. VUE(11) : 图片点击全屏展示
  18. 消息认证码 EMAC
  19. Java高级之Float类和Double类的isNaN()方法
  20. eclipse的主题背景设置(关爱你的眼睛,从这里做起)

热门文章

  1. 什么是python-马哥教育官网-专业Linux培训班,Python培训机构
  2. python中x=x+1的读法-python中a=a+1与a+=1的区别
  3. python中requests库的用途-python中requests库的post请求
  4. python input与返回值-Python 详解基本语法_函数_返回值
  5. python的列表的remove()方法、判断if xxx in xx条件比较耗时问题
  6. lua学习笔记之数据文件及序列化
  7. UVa1587 Box(排序)
  8. Ubuntu14.04安装QQ2013
  9. 题目1192:回文字符串
  10. [Android] for ArcFace Demo