tensorflow 三种模型:ckpt、pb、pb-savemodel
1、CKPT
目录结构
checkpoint:
model.ckpt-1000.index
model.ckpt-1000.data-00000-of-00001
model.ckpt-1000.meta
特点:
首先这种模型文件是依赖 TensorFlow 的,只能在其框架下使用;
数据和图是分开的
这种在训练的时候用的比较多。
代码:就省略了
2、pb模型-只有模型
这种方式只保存了模型的图结构,可以保留隐私的公布到网上。
感觉一些水的论文会用这种方式。
代码:
thanks:https://www.jianshu.com/p/9221fbf52c55
·
import os
import tensorflow as tf
from tensorflow.python.saved_model import builder as saved_model_builder
from tensorflow.python.saved_model import (signature_constants, signature_def_utils, tag_constants, utils) class model():
def __init__(self):
self.a = tf.placeholder(tf.float32, [None])
self.w = tf.Variable(tf.constant(2.0, shape=[1]), name="w")
b = tf.Variable(tf.constant(0.5, shape=[1]), name="b")
self.y = self.a * self.w + b #模型保存为ckpt
def save_model():
graph1 = tf.Graph()
with graph1.as_default():
m = model()
with tf.Session(graph=graph1) as session:
session.run(tf.global_variables_initializer())
update = tf.assign(m.w, [10])
session.run(update)
predict_y = session.run(m.y,feed_dict={m.a:[3.0]})
print(predict_y) saver = tf.train.Saver()
saver.save(session,"model_pb/model.ckpt") #保存为pb模型
def export_model(session, m): #只需要修改这一段,定义输入输出,其他保持默认即可
model_signature = signature_def_utils.build_signature_def(
inputs={"input": utils.build_tensor_info(m.a)},
outputs={
"output": utils.build_tensor_info(m.y)}, method_name=signature_constants.PREDICT_METHOD_NAME) export_path = "pb_model/1"
if os.path.exists(export_path):
os.system("rm -rf "+ export_path)
print("Export the model to {}".format(export_path)) try:
legacy_init_op = tf.group(
tf.tables_initializer(), name='legacy_init_op')
builder = saved_model_builder.SavedModelBuilder(export_path)
builder.add_meta_graph_and_variables(
session, [tag_constants.SERVING],
clear_devices=True,
signature_def_map={
signature_constants.DEFAULT_SERVING_SIGNATURE_DEF_KEY:
model_signature,
},
legacy_init_op=legacy_init_op) builder.save()
except Exception as e:
print("Fail to export saved model, exception: {}".format(e)) #加载pb模型
def load_pb():
session = tf.Session(graph=tf.Graph())
model_file_path = "pb_model/1"
meta_graph = tf.saved_model.loader.load(session, [tf.saved_model.tag_constants.SERVING], model_file_path) model_graph_signature = list(meta_graph.signature_def.items())[0][1]
output_tensor_names = []
output_op_names = []
for output_item in model_graph_signature.outputs.items():
output_op_name = output_item[0]
output_op_names.append(output_op_name)
output_tensor_name = output_item[1].name
output_tensor_names.append(output_tensor_name)
print("load model finish!")
sentences = {}
# 测试pb模型
for test_x in [[1],[2],[3],[4],[5]]:
sentences["input"] = test_x
feed_dict_map = {}
for input_item in model_graph_signature.inputs.items():
input_op_name = input_item[0]
input_tensor_name = input_item[1].name
feed_dict_map[input_tensor_name] = sentences[input_op_name]
predict_y = session.run(output_tensor_names, feed_dict=feed_dict_map)
print("predict pb y:",predict_y) if __name__ == "__main__": save_model() graph2 = tf.Graph()
with graph2.as_default():
m = model()
saver = tf.train.Saver()
with tf.Session(graph=graph2) as session:
saver.restore(session, "model_pb/model.ckpt") #加载ckpt模型
export_model(session, m) load_pb()
3、pb模型-Saved model
这是一种简单格式pb模型保存方式
目录结构
└── 1
···├── saved_model.pb
···└── variables
·········├── variables.data-00000-of-00001
·········└── variables.index
特点:
对于训练好的模型,我们都是用来进行使用的,也就是进行inference。
这个时候就不模型变化了。这种方式就将变量的权重变成了一个常亮。
这样方式模型会变小
在一些嵌入式吗,用C或者C++的系统中,我们也是常用.pb格式的。
代码:
thanks to https://www.jianshu.com/p/9221fbf52c55
import os
import tensorflow as tf
from tensorflow.python.saved_model import builder as saved_model_builder
from tensorflow.python.saved_model import (signature_constants, signature_def_utils, tag_constants, utils) class model():
def __init__(self):
self.a = tf.placeholder(tf.float32, [None])
self.w = tf.Variable(tf.constant(2.0, shape=[1]), name="w")
b = tf.Variable(tf.constant(0.5, shape=[1]), name="b")
self.y = self.a * self.w + b #模型保存为ckpt
def save_model():
graph1 = tf.Graph()
with graph1.as_default():
m = model()
with tf.Session(graph=graph1) as session:
session.run(tf.global_variables_initializer())
update = tf.assign(m.w, [10])
session.run(update)
predict_y = session.run(m.y,feed_dict={m.a:[3.0]})
print(predict_y) saver = tf.train.Saver()
saver.save(session,"model_pb/model.ckpt") #保存为pb模型
def export_model(session, m): #只需要修改这一段,定义输入输出,其他保持默认即可
model_signature = signature_def_utils.build_signature_def(
inputs={"input": utils.build_tensor_info(m.a)},
outputs={
"output": utils.build_tensor_info(m.y)}, method_name=signature_constants.PREDICT_METHOD_NAME) export_path = "pb_model/1"
if os.path.exists(export_path):
os.system("rm -rf "+ export_path)
print("Export the model to {}".format(export_path)) try:
legacy_init_op = tf.group(
tf.tables_initializer(), name='legacy_init_op')
builder = saved_model_builder.SavedModelBuilder(export_path)
builder.add_meta_graph_and_variables(
session, [tag_constants.SERVING],
clear_devices=True,
signature_def_map={
signature_constants.DEFAULT_SERVING_SIGNATURE_DEF_KEY:
model_signature,
},
legacy_init_op=legacy_init_op) builder.save()
except Exception as e:
print("Fail to export saved model, exception: {}".format(e)) #加载pb模型
def load_pb():
session = tf.Session(graph=tf.Graph())
model_file_path = "pb_model/1"
meta_graph = tf.saved_model.loader.load(session, [tf.saved_model.tag_constants.SERVING], model_file_path) model_graph_signature = list(meta_graph.signature_def.items())[0][1]
output_tensor_names = []
output_op_names = []
for output_item in model_graph_signature.outputs.items():
output_op_name = output_item[0]
output_op_names.append(output_op_name)
output_tensor_name = output_item[1].name
output_tensor_names.append(output_tensor_name)
print("load model finish!")
sentences = {}
# 测试pb模型
for test_x in [[1],[2],[3],[4],[5]]:
sentences["input"] = test_x
feed_dict_map = {}
for input_item in model_graph_signature.inputs.items():
input_op_name = input_item[0]
input_tensor_name = input_item[1].name
feed_dict_map[input_tensor_name] = sentences[input_op_name]
predict_y = session.run(output_tensor_names, feed_dict=feed_dict_map)
print("predict pb y:",predict_y) if __name__ == "__main__": save_model() graph2 = tf.Graph()
with graph2.as_default():
m = model()
saver = tf.train.Saver()
with tf.Session(graph=graph2) as session:
saver.restore(session, "model_pb/model.ckpt") #加载ckpt模型
export_model(session, m) load_pb()
tensorflow 三种模型:ckpt、pb、pb-savemodel的更多相关文章
- SDN三种模型解析
数十年前,计算机科学家兼网络作家Andrew S. Tanenbaum讽刺标准过多难以选择,当然现在也是如此,比如软件定义网络模型的数量也很多.但是在考虑部署软件定义网络(SDN)或者试点之前,首先需 ...
- Javascript事件模型系列(一)事件及事件的三种模型
一.开篇 在学习javascript之初,就在网上看过不少介绍javascript事件的文章,毕竟是js基础中的基础,文章零零散散有不少,但遗憾的是没有看到比较全面的系列文章.犹记得去年这个时候,参加 ...
- PHP.23-ThinkPHP框架的三种模型实例化-(D()方法与M()方法的区别)
三种模型实例化 原则上:每个数据表应对应一个模型类(Home/Model/GoodsModel.class.php --> 表tp_goods) 1.直接实例化 和实例化其他类库一样实例化模型类 ...
- C语言提高 (3) 第三天 二级指针的三种模型 栈上指针数组、栈上二维数组、堆上开辟空间
1 作业讲解 指针间接操作的三个必要条件 两个变量 其中一个是指针 建立关联:用一个指针指向另一个地址 * 简述sizeof和strlen的区别 strlen求字符串长度,字符数组到’\0’就结束 s ...
- tensorflow模型ckpt转pb以及其遇到的问题
使用tensorflow训练模型,ckpt作为tensorflow训练生成的模型,可以在tensorflow内部使用.但是如果想要永久保存,最好将其导出成pb的形式. tensorflow已经准备好c ...
- ZeroMQ - 三种模型的python实现
ZeroMQ是一个消息队列网络库,实现网络常用技术封装.在C/S中实现了三种模式,这段时间用python简单实现了一下,感觉python虽然灵活.但是数据处理不如C++自由灵活. 1.Request- ...
- tensorFlow 三种启动图的用法
tf.Session(),tf.InteractivesSession(),tf.train.Supervisor().managed_session() 用法的区别: tf.Session() 构 ...
- zmq 三种模型的python实现
1.Request-Reply模式: 客户端在请求后,服务端必须回响应 server: #!/usr/bin/python #-*-coding:utf-8-*- import time import ...
- ESPlatform 支持的三种群集模型 —— ESFramework通信框架 4.0 进阶(09)
对于最多几千人同时在线的通信应用,通常使用单台服务器就可以支撑.但是,当同时在线的用户数达到几万.几十万.甚至百万的时候,我们就需要很多的服务器来分担负载.但是,依据什么规则和结构来组织这些服务器,并 ...
随机推荐
- 数据可视化之PowerQuery篇(十六)使用Power BI进行流失客户分析
https://zhuanlan.zhihu.com/p/73358029 为了提升销量,在不断吸引新客户的同时,还要防止老客户离你而去,但每一个顾客不可能永远是你的客户,不可避免的都会经历新客户.活 ...
- 从JDK源码理解java引用
目录 java中的引用 引用队列 虚引用.弱引用.软引用的实现 ReferenceHandler线程 引用队列的实现 总结 参考资料 java中的引用 JDK 1.2之后,把对象的引用分为了四种类型, ...
- Crystal Reports --报表设计
完整的报表解决方案 数据访问—>报表设计—>报表管理—>与应用系统集成 一.规划报表 设计报表的准备工作 谁看报表? 报表的数据是什么?(页眉页脚的内容?是否需要分组?是否需要汇总? ...
- Linux/Docker 中使用 System.Drawing.Common 踩坑小计
前言 在项目迁移到 .net core 上面后,我们可以使用 System.Drawing.Common 组件来操作 Image,Bitmap 类型,实现生成验证码.二维码,图片操作等功能.Syste ...
- HashMap源码实现分析
HashMap源码实现分析 一.前言 HashMap 顾名思义,就是用hash表的原理实现的Map接口容器对象,那什么又是hash表呢. 我们对数组都很熟悉,数组是一个占用连续内存的数据结构,学过C的 ...
- SW算法求全局最小割(Stoer-Wagner算法)
我找到的唯一能看懂的题解:[ZZ]最小割集Stoer-Wagner算法 似乎是一个冷门算法,连oi-wiki上都没有,不过洛谷上竟然有它的模板题,并且2017百度之星的资格赛还考到了.于是来学习一下. ...
- No implementation found for void `org.webrtc.PeerConnectionFactory.initializeAndroidGlobals(android.content.Context, boolean)
背景介绍 最近在使用 AndroidRTC 利用WebRtc屏幕共享时使用PeerConnectionFactory.initializeAndroidGlobals(context, true, t ...
- 在ASP.NET Core中创建自定义端点可视化图
在上篇文章中,我为构建自定义端点可视化图奠定了基础,正如我在第一篇文章中展示的那样.该图显示了端点路由的不同部分:文字值,参数,动词约束和产生结果的端点: 在本文中,我将展示如何通过创建一个自定义的D ...
- Spring Cache缓存注解
目录 Spring Cache缓存注解 @Cacheable 键生成器 @CachePut @CacheEvict @Caching @CacheConfig Spring Cache缓存注解 本篇文 ...
- 第十二章 类加载器&反射
12.1.类加载器 12.1.1.类加载 当程序要使用某个类时,如果该类还未被加载到内存中,则系统会通过类的加载.类的连接.类的初始化这三个步骤来对类进行初始化.如果不出现意外情况,JVM将会连续完成 ...