Tensorflow 将训练模型保存为pd文件
前言
保存 模型有2种方法。
方法
1.使用TensorFlow模型保存函数
save = tf.train.Saver()
......
saver.save(sess,"checkpoint/model.ckpt",global_step=step)*
得到3个结果
model.ckpt-129220.data-00000-of-00001#保存了模型的所有变量的值。
model.ckpt-129220.index
model.ckpt-129220.meta # 保存了graph结构,包括GraphDef, SaverDef等。存在时,可以不在文件中定义模型,也可以运行
再将这3个文件保存为.pd文件
import tensorflow as tf
import deeplab_model
def export_graph(model, checkpoint_dir, model_name):
...
model: the defined model
checkpoint_dir: the dir of three files
model_name: the name of .pb
...
graph = tf.Graph()
with graph.as_default():
### 输入占位符
input_img = tf.placeholder(tf.float32, shape=[None, None, None, 3], name='input_image')
labels = tf.zeros([1, 512, 512,1])
labels = tf.to_int32(tf.image.convert_image_dtype(labels, dtype=tf.uint8))
### 需要输出的Tensor
output = model.deeplabv3_plus_model_fn(
input_img,
labels,
tf.estimator.ModeKeys.EVAL,
params={
'output_stride': 16,
'batch_size': 1, # Batch size must be 1 because the images' size may differ
'base_architecture': 'resnet_v2_50',
'pre_trained_model': None,
'batch_norm_decay': None,
'num_classes': 2,
'freeze_batch_norm': True
}).predictions['classes']
### 给输出的tensor命名
output = tf.identity(output, name='output_label')
restore_saver = tf.train.Saver()
with tf.Session(graph=graph) as sess:
### 初始化变量
sess.run(tf.global_variables_initializer())
### load the model
restore_saver.restore(sess, checkpoint_dir)
output_graph_def = tf.graph_util.convert_variables_to_constants(
sess, graph.as_graph_def(), [output.op.name])
### 将图写成.pb文件
tf.train.write_graph(output_graph_def, 'pretrained', model_name, as_text=False)
### 调用函数,生成.pd文件
export_graph(deeplab_model, 'model/model.ckpt-133958', 'model.pd')
### 读取
import tensorflow as tf
import os
def inference():
with tf.gfile.FastGFile('pretrained/model.pd', 'rb') as model_file:
graph = tf.Graph()
graph_def = tf.GraphDef()
graph_def.ParseFromString(model_file.read())
[output_image] = tf.import_graph_def(graph_def,
input_map={'input_image': images},
return_elements=['output_label:0'],
name='output')
sess = tf.Session()
label = sess.run(output_image)
return label
labels = inference()
2.直接保存
import tensorflow as tf
from tensorflow.python.framework import graph_util
var1 = tf.Variable(1.0, dtype=tf.float32, name='v1')
var2 = tf.Variable(2.0, dtype=tf.float32, name='v2')
var3 = tf.Variable(2.0, dtype=tf.float32, name='v3')
x = tf.placeholder(dtype=tf.float32, shape=None, name='x')
x2 = tf.placeholder(dtype=tf.float32, shape=None, name='x2')
addop = tf.add(x, x2, name='add')
addop2 = tf.add(var1, var2, name='add2')
addop3 = tf.add(var3, var2, name='add3')
initop = tf.global_variables_initializer()
model_path = './Test/model.pb'
with tf.Session() as sess:
sess.run(initop)
print(sess.run(addop, feed_dict={x: 12, x2: 23}))
output_graph_def = graph_util.convert_variables_to_constants(sess, sess.graph_def, ['add', 'add2', 'add3'])
# 将计算图写入到模型文件中
model_f = tf.gfile.FastGFile(model_path, mode="wb")
model_f.write(output_graph_def.SerializeToString())
####读取代码:
import tensorflow as tf
with tf.Session() as sess:
model_f = tf.gfile.FastGFile("./Test/model.pb", mode='rb')
graph_def = tf.GraphDef()
graph_def.ParseFromString(model_f.read())
c = tf.import_graph_def(graph_def, return_elements=["add2:0"])
c2 = tf.import_graph_def(graph_def, return_elements=["add3:0"])
x, x2, c3 = tf.import_graph_def(graph_def, return_elements=["x:0", "x2:0", "add:0"])
print(sess.run(c))
print(sess.run(c2))
print(sess.run(c3, feed_dict={x: 23, x2: 2}))
Tensorflow 将训练模型保存为pd文件的更多相关文章
- tensorflow 保存训练模型ckpt 查看ckpt文件中的变量名和对应值
TensorFlow 模型保存与恢复 一个快速完整的教程,以保存和恢复Tensorflow模型. 在本教程中,我将会解释: TensorFlow模型是什么样的? 如何保存TensorFlow模型? 如 ...
- [翻译] Tensorflow模型的保存与恢复
翻译自:http://cv-tricks.com/tensorflow-tutorial/save-restore-tensorflow-models-quick-complete-tutorial/ ...
- 超详细的Tensorflow模型的保存和加载(理论与实战详解)
1.Tensorflow的模型到底是什么样的? Tensorflow模型主要包含网络的设计(图)和训练好的各参数的值等.所以,Tensorflow模型有两个主要的文件: a) Meta graph: ...
- tensorflow模型的保存与恢复,以及ckpt到pb的转化
转自 https://www.cnblogs.com/zerotoinfinity/p/10242849.html 一.模型的保存 使用tensorflow训练模型的过程中,需要适时对模型进行保存,以 ...
- 『TensorFlow』模型保存和载入方法汇总
『TensorFlow』第七弹_保存&载入会话_霸王回马 一.TensorFlow常规模型加载方法 保存模型 tf.train.Saver()类,.save(sess, ckpt文件目录)方法 ...
- tensorflow模型持久化保存和加载
模型文件的保存 tensorflow将模型保持到本地会生成4个文件: meta文件:保存了网络的图结构,包含变量.op.集合等信息 ckpt文件: 二进制文件,保存了网络中所有权重.偏置等变量数值,分 ...
- 2018百度之星开发者大赛-paddlepaddle学习(二)将数据保存为recordio文件并读取
paddlepaddle将数据保存为recordio文件并读取 因为有时候一次性将数据加载到内存中有可能太大,所以我们可以选择将数据转换成标准格式recordio文件并读取供我们的网络利用,接下来记录 ...
- Tensorflow模型变量保存
Tensorflow:模型变量保存 觉得有用的话,欢迎一起讨论相互学习~Follow Me 参考文献Tensorflow实战Google深度学习框架 实验平台: Tensorflow1.4.0 pyt ...
- tensorflow模型持久化保存和加载--深度学习-神经网络
模型文件的保存 tensorflow将模型保持到本地会生成4个文件: meta文件:保存了网络的图结构,包含变量.op.集合等信息 ckpt文件: 二进制文件,保存了网络中所有权重.偏置等变量数值,分 ...
随机推荐
- ArrayQueue(队列)
code1: #include <stdio.h> #include <conio.h> #include <stdlib.h> #define MAXSIZE 6 ...
- office365激活码序列号密钥:
亲测可用: NGCM9-FWB6X-9WKYC-GRWVD-63B3P
- SpringBoot常用注解解析
@RestController 将返回的对象数据直接以 JSON 或 XML 形式写入 HTTP 响应(Response)中.绝大部分情况下都是直接以 JSON 形式返回给客户端,很少的情况下才会以 ...
- sublime3常用环境配置
如何设置侧边栏颜色 Ctrl+Shift+P -> install -> 搜索安装包SyncedSidebarBg,自动同步侧边栏底色为编辑窗口底色. 设置快捷键让html文件在浏览器窗口 ...
- 孤荷凌寒自学python第103天认识区块链017
[主要内容] 今天继续分析从github上获取的开源代码怎么实现简单区块链的入门知识,共用时间25分钟. (此外整理作笔记花费了约34分钟) 详细学习过程见文末学习过程屏幕录像. 今天所作的工作是进一 ...
- 杭电 2028 ( Lowest Common Multiple Plus )
链接:http://acm.split.hdu.edu.cn/showproblem.php?pid=2028 题目要求:就是求最大公倍数,我百度了一下,最好实现的算法就是: 公式法 由于 ...
- Java基础 -1.3
CLASSPATH 为了 可以在不同的目录中都可以执行d:\java\Hello.class文件 只能够依靠CLASSPATH环境变量 在cmd中 SET CLASSPATH = d:\java 当设 ...
- 建设基于TensorFlow的深度学习环境
一.使用yum安装git 1.查看系统是否已经安装git git --version 2.yum 安装git yum install git 3.安装成功 git --version 4.进入指定目录 ...
- Codeforces Round #580 (Div. 2)D(思维,Floyd暴力最小环)
#define HAVE_STRUCT_TIMESPEC#include<bits/stdc++.h>using namespace std;const int maxn=300;cons ...
- Controller 层类
package com.thinkgem.jeesite.modules.yudengji.web; import java.util.Date; import javax.servlet.http. ...