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的更多相关文章

  1. SDN三种模型解析

    数十年前,计算机科学家兼网络作家Andrew S. Tanenbaum讽刺标准过多难以选择,当然现在也是如此,比如软件定义网络模型的数量也很多.但是在考虑部署软件定义网络(SDN)或者试点之前,首先需 ...

  2. Javascript事件模型系列(一)事件及事件的三种模型

    一.开篇 在学习javascript之初,就在网上看过不少介绍javascript事件的文章,毕竟是js基础中的基础,文章零零散散有不少,但遗憾的是没有看到比较全面的系列文章.犹记得去年这个时候,参加 ...

  3. PHP.23-ThinkPHP框架的三种模型实例化-(D()方法与M()方法的区别)

    三种模型实例化 原则上:每个数据表应对应一个模型类(Home/Model/GoodsModel.class.php --> 表tp_goods) 1.直接实例化 和实例化其他类库一样实例化模型类 ...

  4. C语言提高 (3) 第三天 二级指针的三种模型 栈上指针数组、栈上二维数组、堆上开辟空间

    1 作业讲解 指针间接操作的三个必要条件 两个变量 其中一个是指针 建立关联:用一个指针指向另一个地址 * 简述sizeof和strlen的区别 strlen求字符串长度,字符数组到’\0’就结束 s ...

  5. tensorflow模型ckpt转pb以及其遇到的问题

    使用tensorflow训练模型,ckpt作为tensorflow训练生成的模型,可以在tensorflow内部使用.但是如果想要永久保存,最好将其导出成pb的形式. tensorflow已经准备好c ...

  6. ZeroMQ - 三种模型的python实现

    ZeroMQ是一个消息队列网络库,实现网络常用技术封装.在C/S中实现了三种模式,这段时间用python简单实现了一下,感觉python虽然灵活.但是数据处理不如C++自由灵活. 1.Request- ...

  7. tensorFlow 三种启动图的用法

    tf.Session(),tf.InteractivesSession(),tf.train.Supervisor().managed_session()  用法的区别: tf.Session() 构 ...

  8. zmq 三种模型的python实现

    1.Request-Reply模式: 客户端在请求后,服务端必须回响应 server: #!/usr/bin/python #-*-coding:utf-8-*- import time import ...

  9. ESPlatform 支持的三种群集模型 —— ESFramework通信框架 4.0 进阶(09)

    对于最多几千人同时在线的通信应用,通常使用单台服务器就可以支撑.但是,当同时在线的用户数达到几万.几十万.甚至百万的时候,我们就需要很多的服务器来分担负载.但是,依据什么规则和结构来组织这些服务器,并 ...

随机推荐

  1. socket采用epoll编程demo

    epoll工作流程 首先,需要调用epoll_create创建epoll: 此后我们就可以进行socket/bind/listen: 然后调用epoll_ctl进行注册: 接下来,就可以通过一个whi ...

  2. 从零开始学Electron笔记(六)

    在之前的文章我们介绍了一下Electron如何通过链接打开浏览器和嵌入网页,接下来我们继续说一下Electron中的对话框 Dialog和消息通知 Notification. 在之前的文章中其实我们是 ...

  3. 阿里面试官:这些软件测试面试题都答对了,I want you!

    [ 你悄悄来,请记得带走一丝云彩 ] 测试岗必知必会 01请描述如何划分缺陷与错误严重性和优先级别? 给软件缺陷与错误划分严重性和优先级的通用原则: 1. 表示软件缺陷所造成的危害和恶劣程度. 2. ...

  4. GPO - Disabling Task Manager Access

    Create a GPO to disable Task Manager Access to normal users. Add an exception to Domain Admins.

  5. CSS3伪类 :empty

    :empty 种类:伪类选择器 版本:CSS3.0 用法:匹配每个没有子元素(包含文本)的元素. 例子: <!DOCTYPE html> <html> <head> ...

  6. vue-cli 2.x和3.x配置移动端适配px自动转为rem

    移动端适配一直都是个大问题,现在也出现了各种各样的解决方案,比如 rem, vw 百分比等,但是比较成熟的切比较容易编写的还是 rem,他是相对于根元素的 font-size 进行等比例计算的. 但是 ...

  7. Oracle对表进行备份

    前言: 在实际开发中,我们常常需要对单张或多张表进行备份,以下博主就从这两个方面进行总结.如需转载,请标明来处,谢谢! 在备份前我们先创建表盒相关测试的数据 -- Create table creat ...

  8. 关于C# winform唤起本地已安装应用程序(测试win10,win7可用)

    想要唤起本地已安装应用程序,我想到的有三种可行的方法: 第一种就是打开本地的快捷方式(有的应用可能没有快捷方式,但这种方法效率最高,可配合其他方法使用),快捷方式分为本地桌面快捷方式和开始菜单中的快捷 ...

  9. scrapy中选择器用法

    一.Selector选择器介绍 python从网页中提取数据常用以下两种方法: lxml:基于ElementTree的XML解析库(也可以解析HTML),不是python的标准库 BeautifulS ...

  10. laravel报错1071 Specified key was too long; max key length is 1000 bytes

    Laravel 默认使用utf8mb4字符编码,而不是的utf8编码.因此运行php artisan migrate会出现如下错误: [Illuminate\Database\QueryExcepti ...