生成可转换为.pb文件之前的准备工作

 model.fit(self.x_train, self.y_train, batch_size=self.batch_size, epochs=self.epoch_size, class_weight = 'auto',validation_split=0.1)print("savemodel---------------")model.save_weights('tmp/model3_3.h5')model.save('tmp/model3_3.hdf5')json_string = model.to_json()open('tmp/model3.json', 'w').write(json_string)#输出损失和精确度score = model.evaluate(self.x_test, self.y_test, batch_size=self.batch_size)

调用此封装模型

import warnings
warnings.filterwarnings("ignore", category=Warning)
warnings.filterwarnings("ignore", category=FutureWarning)import keras
import cv2 as cv
import numpy as np
from yaotie3.painting import *
from keras.models import model_from_yaml
from keras.preprocessing.image import img_to_array
# from keras import backend as K
# K.clear_session()
np.set_printoptions(suppress=True)dir = "test/L518.jpg"yaml_string = open('tmp/model3.json').read()
model = model_from_yaml(yaml_string)
classifier = model.load_weights('tmp/model3_3.h5')img = cv.imread(dir, -1)
img = img_to_array(img)/ 255
img = np.expand_dims(img, axis=0)
print(model.predict(img))

转为.pb文件

import warnings
warnings.filterwarnings("ignore", category=Warning)
warnings.filterwarnings("ignore", category=FutureWarning)import sys
from keras.models import load_model
import tensorflow as tf
import os
import os.path as osp
from keras import backend as K
from tensorflow.python.framework.graph_util import convert_variables_to_constantsdef freeze_session(session, keep_var_names=None, output_names=None, clear_devices=True):# 将会话状态冻结为已删除的计算图,创建一个新的计算图,其中变量节点由在会话中获取其当前值的常量替换.# session要冻结的TensorFlow会话,keep_var_names不应冻结的变量名列表,或者无冻结图中的所有变量# output_names相关图输出的名称,clear_devices从图中删除设备以获得更好的可移植性graph = session.graphwith graph.as_default():freeze_var_names = list(set(v.op.name for v in tf.global_variables()).difference(keep_var_names or []))output_names = output_names or []output_names += [v.op.name for v in tf.global_variables()]input_graph_def = graph.as_graph_def()# 从图中删除设备以获得更好的可移植性if clear_devices:for node in input_graph_def.node:node.device = ""# 用相同值的常量替换图中的所有变量frozen_graph = convert_variables_to_constants(session, input_graph_def, output_names, freeze_var_names)return frozen_graphoutput_fld = sys.path[0] + '/tmp/'
if not os.path.isdir(output_fld):os.mkdir(output_fld)
weight_file_path = osp.join(sys.path[0], 'tmp/model3_3.hdf5')
K.set_learning_phase(0)
net_model = load_model(weight_file_path)print('input is :', net_model.input.name)
print ('output is:', net_model.output.name)# 获得当前图
sess = K.get_session()
# 冻结图
frozen_graph = freeze_session(sess, output_names=[net_model.output.op.name])from tensorflow.python.framework import graph_io
graph_io.write_graph(frozen_graph, output_fld, 'new_tensor_model.pb', as_text=False)
print('saved the constant graph (ready for inference) at: ', osp.join(output_fld, 'new_tensor_model.pb'))
print (K.get_uid())

调用.pb模型

import warnings
warnings.filterwarnings("ignore", category=Warning)
warnings.filterwarnings("ignore", category=FutureWarning)import tensorflow as tf
import numpy as np
import os
import cv2 as cv
import sysdef predict(jpg_path):pb_file_path ='./tmp/new_tensor_model.pb'print(pb_file_path)with tf.Graph().as_default():output_graph_def = tf.GraphDef()with open(pb_file_path, "rb") as f:output_graph_def.ParseFromString(f.read())tensors = tf.import_graph_def(output_graph_def, name="")# print (tensors)with tf.Session() as sess:init = tf.global_variables_initializer()sess.run(init)sess.graph.get_operations()input_x = sess.graph.get_tensor_by_name("input_1:0")  # 具体名称看上一段代码的input.nameout_softmax = sess.graph.get_tensor_by_name("dense_2/Softmax:0")  # 具体名称看上一段代码的output.nameimg = cv.imread(jpg_path, -1)img_out_softmax = sess.run(out_softmax, feed_dict={input_x: np.array(img).reshape((-1, 350, 350, 1)) / 255})print(img_out_softmax)return img_out_softmax
#
rootdir = "test/L518.jpg"if __name__ == '__main__':index = predict(rootdir)print (index, type(index))

生成.pbtxt

import warnings
warnings.filterwarnings("ignore", category=Warning)
warnings.filterwarnings("ignore", category=FutureWarning)
import tensorflow as tf
from tensorflow.python.platform import gfile# 函数功能能,将pb模型转换为pbtxt,转换好后存储到当前目录下,模型名字是protobuf.pbtxt
def convert_pb_to_pbtxt(filename):with gfile.FastGFile(filename, 'rb') as f:graph_def = tf.GraphDef()graph_def.ParseFromString(f.read())tf.import_graph_def(graph_def, name='')tf.train.write_graph(graph_def, './', 'tmp/protobuf.pbtxt', as_text=True)return# 函数功能能,将pb模型转换为txt,转换好后存储到txtmodel文件夹下,模型名字是frozen_model_test.txt
def pb_to_txt(frozen_graph_filename):with tf.gfile.GFile(frozen_graph_filename, "rb") as f:graph_def = tf.GraphDef()graph_def.ParseFromString(f.read())tf.import_graph_def(graph_def, name='')tf.train.write_graph(graph_def, "./txtmodel ", 'frozen_model_test.txt', as_text=True)if __name__ == '__main__':# mygraph = pb_to_txt("frozen_inference_graph.pb")filepath = 'tmp/new_tensor_model.pb'convert_pb_to_pbtxt(filepath)

将keras的模型封装成可转换为tensorlow的.pb格式,并生成.pbtxt文件相关推荐

  1. PROE二次开发(protoolkit):把PRT或者ASM模型转换成STEP,PS,IGES,CATIA等等格式

    PROE强大的参数化建模能力在各种领域应用广泛.本文讨论三个函数:ProRasterFileWrite,ProIntf3DFileWrite和ProPDFExport 这三个函数的共同特点是导出模型, ...

  2. axure 转换为html,AxureRP教程AxureRP如何生成HTML文件

    1.正常打开一份已经设计好的RP,如下截图所示: 2.点击上方菜单的"发布"按钮,在弹出的选项中单击"生成HTML文件",详细操作如下图标红位置. 3.在弹出的 ...

  3. python封装成exe win7不能用_pyinstaller打包python的执行文件如何在32位和64位操作系统下也能运行...

    我在64位的windows 10 操作系统下,用64位Python环境,PyInstaller 打包一个py程序. 如 pyinstaller -F -w my.py 你会看到一些警告信息WARNIN ...

  4. 数据标签处理:python将xml文件转换为txt,csv格式

    数据标签处理:python将xml文件转换为txt,csv格式 这里的标注文件为点标注文件 每次要用数据处理脚本的时候都忘记放哪里了,然后重写了一遍又一遍,虽然代码不长,但是每次都有重新写还是很麻烦, ...

  5. keras提取模型中的某一层_Tensorflow笔记:高级封装——Keras

    前言 之前在<Tensorflow笔记:高级封装--tf.Estimator>中介绍了Tensorflow的一种高级封装,本文介绍另一种高级封装Keras.Keras的特点就是两个字--简 ...

  6. keras模型转换为tensorflow的pb模型结构

    官方文档介绍如下, 此时博主电脑环境配置为:tensorflow-gpu 2.4.0.python3.6.cuda11.0.cudnn8.0,详细信息可见博主这篇博客 应用 Applications ...

  7. java中如何把时间封装成类,java-如何在不使用任何不推荐使用的类的情况下将日期从一种格式转换为另一种格式的日期对象?...

    java-如何在不使用任何不推荐使用的类的情况下将日期从一种格式转换为另一种格式的日期对象? 我想将date1格式的日期转换为date2格式的日期对象. SimpleDateFormat simple ...

  8. 如何将自己写的verilog模块封装成IP核(二)

    =======================第一篇======================= 如何将自己写的verilog模块封装成IP核 将你的设计制作成BlackBox,也就是网表文件,这样 ...

  9. python模型保存save_浅谈keras保存模型中的save()和save_weights()区别

    今天做了一个关于keras保存模型的实验,希望有助于大家了解keras保存模型的区别. 我们知道keras的模型一般保存为后缀名为h5的文件,比如final_model.h5.同样是h5文件用save ...

  10. hibernate将本地SQL查询结果封装成对象

    hibernate将本地SQL查询结果封装成对象 不知道大家有没有碰过这种情况,迫于很多情况只能用native SQL来查询(如:复杂统计等),然而使用native查询后,结果会被放到object里, ...

最新文章

  1. mysql安全权限的讲解
  2. 单片机小白学步系列(十) 单片机程序下载相关知识
  3. k8s创建pod加入容器_K8S架构原理及其工作流程
  4. create_proc_read_entry中函数的说名
  5. 米熊科技:给烘培加点“云”的味道
  6. 工作流实战_12_flowable 流程实例 终止流程
  7. C++虚继承的实现原理、内存分布、作用
  8. 解决tomcat的undeploy
  9. MongoDB3.x中添加用户和权限控制
  10. /usr/bin/ld: cannot find Scrt1.o: No such file or directory
  11. 五位数电话号码以及中国各市区号
  12. SmartBi参数传值与JS报表宏及Mysql数据集特殊功能总结
  13. Vue 事件处理 -- 事件修饰符(prevent、stop、capture、self、once)
  14. 基于 FPGA 的数字表示
  15. 在计算机领域做研究的一些想法
  16. 数字0是奇数还是偶数_C程序检查数字是偶数还是奇数
  17. Android 进阶笔记,包含常用的技术框架、博客社区、书籍等。
  18. 知识付费对接微信公众号订阅消息
  19. LDA-线性判别分析(一)预备知识
  20. CV街景门牌号码识别02_数据读取与增广

热门文章

  1. 车辆模型-跟踪误差模型
  2. VMware激活密钥
  3. Training ICD Basics摘要
  4. java全栈工程师简历,全栈工程师:全栈JavaScript简介
  5. oracle修改asm参数文件,修改asm中的spfile参数
  6. arm解锁 j-flash_jlink驱动下载(SEGGER J-FlASH ARM)
  7. 斯皮尔曼相关系数范围_什么是斯皮尔曼相关系数
  8. LiteOS学习笔记-8LiteOS SDK oc流程之LwM2M
  9. android控制灯编程,远程控制智能灯(android)
  10. 电子书格式问题的本质