前言

保存 模型有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文件的更多相关文章

  1. tensorflow 保存训练模型ckpt 查看ckpt文件中的变量名和对应值

    TensorFlow 模型保存与恢复 一个快速完整的教程,以保存和恢复Tensorflow模型. 在本教程中,我将会解释: TensorFlow模型是什么样的? 如何保存TensorFlow模型? 如 ...

  2. [翻译] Tensorflow模型的保存与恢复

    翻译自:http://cv-tricks.com/tensorflow-tutorial/save-restore-tensorflow-models-quick-complete-tutorial/ ...

  3. 超详细的Tensorflow模型的保存和加载(理论与实战详解)

    1.Tensorflow的模型到底是什么样的? Tensorflow模型主要包含网络的设计(图)和训练好的各参数的值等.所以,Tensorflow模型有两个主要的文件: a) Meta graph: ...

  4. tensorflow模型的保存与恢复,以及ckpt到pb的转化

    转自 https://www.cnblogs.com/zerotoinfinity/p/10242849.html 一.模型的保存 使用tensorflow训练模型的过程中,需要适时对模型进行保存,以 ...

  5. 『TensorFlow』模型保存和载入方法汇总

    『TensorFlow』第七弹_保存&载入会话_霸王回马 一.TensorFlow常规模型加载方法 保存模型 tf.train.Saver()类,.save(sess, ckpt文件目录)方法 ...

  6. tensorflow模型持久化保存和加载

    模型文件的保存 tensorflow将模型保持到本地会生成4个文件: meta文件:保存了网络的图结构,包含变量.op.集合等信息 ckpt文件: 二进制文件,保存了网络中所有权重.偏置等变量数值,分 ...

  7. 2018百度之星开发者大赛-paddlepaddle学习(二)将数据保存为recordio文件并读取

    paddlepaddle将数据保存为recordio文件并读取 因为有时候一次性将数据加载到内存中有可能太大,所以我们可以选择将数据转换成标准格式recordio文件并读取供我们的网络利用,接下来记录 ...

  8. Tensorflow模型变量保存

    Tensorflow:模型变量保存 觉得有用的话,欢迎一起讨论相互学习~Follow Me 参考文献Tensorflow实战Google深度学习框架 实验平台: Tensorflow1.4.0 pyt ...

  9. tensorflow模型持久化保存和加载--深度学习-神经网络

    模型文件的保存 tensorflow将模型保持到本地会生成4个文件: meta文件:保存了网络的图结构,包含变量.op.集合等信息 ckpt文件: 二进制文件,保存了网络中所有权重.偏置等变量数值,分 ...

随机推荐

  1. 九、web.xml理解

    1.web.xml文件在每个web工程不是必须要有的:     web.xml文件是用来初始化配置信息:比如Welcome页面.servlet.servlet-mapping.filter.liste ...

  2. CentOS7 安装 OpenCV 的一些问题解决办法

    由于强迫症,实在受不了root权限的旧gcc才能使用boost而普通权限却是最新版gcc,经过一番折腾后,终于把配置全部弄好了,实际上就只需要把新版gcc的各个文件放到系统找到旧gcc的地方,并建立新 ...

  3. C/C++网络编程3——地址族与数据序列

    C/C++网络编程2中介绍了套接字,这一节介绍给套接字分配ip和端口号.ip用于标识一台主机,端口号用于标识一个主机中的一个应用程序,端口号占16位,0到65535,其中0到1023是知名端口号. 表 ...

  4. vue学习笔记:vue的认识与特点与获取

    Vue了解 Vue:读作 view Vue是一个渐进式框架 与其他重量级框架不同的是,Vue 采用自底向上增量开发的设计. Vue 的核心库只关注视图层,并且非常容易学习,非常容易与其它库或已有项目整 ...

  5. selenium webdriver 常用方法

    /** * 判断元素是否存在 * * @param driver * @param by * @return */ public static boolean isElementPresent(Web ...

  6. frp 配置

    前言 对于没有公网 IP 的内网用户来说,远程管理或在外网访问内网机器上的服务是一个问题. 今天给大家介绍一款好用内网穿透工具 FRP,FRP 全名:Fast Reverse Proxy.FRP 是一 ...

  7. Windows程序设计学习笔记(1):一个简单的windows程序

    <Windows程序设计>(第五版)(美Charles Petzold著) #include<windows.h> LRESULT CALLBACK WndProc(HWND, ...

  8. redis 高级学习和应用场景

    redis 高级学习 1.redis 复制 2.redis 集群 3.哨兵机制 4.spring 与哨兵结合 5.数据恢复与转移 6.redis 的阻塞分析 redis 实战 1. 数据缓存(热点数据 ...

  9. IIS 应用程序池回收(代码实现)

    回收 public void StartStopRecycleApp(string appName = "项目DLL名称", string method = "Recyc ...

  10. Android。WebView加载UR请求使用Cookie储存User_Id记录用户是否登陆过

    1.WebView初始化的时候用倒如下代码: if (Build.VERSION.SDK_INT >= 21) { CookieManager.getInstance().setAcceptTh ...