h5_to_pb.py

from keras.models import load_model
import tensorflow as tf
import os
import os.path as osp
from keras import backend as K
#路径参数
input_path = 'input path'
weight_file = 'weight.h5'
weight_file_path = osp.join(input_path,weight_file)
output_graph_name = weight_file[:-3] + '.pb'
#转换函数
def h5_to_pb(h5_model,output_dir,model_name,out_prefix = "output_",log_tensorboard = True):
if osp.exists(output_dir) == False:
os.mkdir(output_dir)
out_nodes = []
for i in range(len(h5_model.outputs)):
out_nodes.append(out_prefix + str(i + 1))
tf.identity(h5_model.output[i],out_prefix + str(i + 1))
sess = K.get_session()
from tensorflow.python.framework import graph_util,graph_io
init_graph = sess.graph.as_graph_def()
main_graph = graph_util.convert_variables_to_constants(sess,init_graph,out_nodes)
graph_io.write_graph(main_graph,output_dir,name = model_name,as_text = False)
if log_tensorboard:
from tensorflow.python.tools import import_pb_to_tensorboard
import_pb_to_tensorboard.import_to_tensorboard(osp.join(output_dir,model_name),output_dir)
#输出路径
output_dir = osp.join(os.getcwd(),"trans_model")
#加载模型
h5_model = load_model(weight_file_path)
h5_to_pb(h5_model,output_dir = output_dir,model_name = output_graph_name)
print('model saved')

将转换成的pb模型进行加载

load_pb.py

import tensorflow as tf
from tensorflow.python.platform import gfile def load_pb(pb_file_path):
sess = tf.Session()
with gfile.FastGFile(pb_file_path, 'rb') as f:
graph_def = tf.GraphDef()
graph_def.ParseFromString(f.read())
sess.graph.as_default()
tf.import_graph_def(graph_def, name='') print(sess.run('b:0'))
#输入
input_x = sess.graph.get_tensor_by_name('x:0')
input_y = sess.graph.get_tensor_by_name('y:0')
#输出
op = sess.graph.get_tensor_by_name('op_to_store:0')
#预测结果
ret = sess.run(op, {input_x: 3, input_y: 4})
print(ret)

最新文章

  1. RakNet基本教程
  2. php基础面试题1
  3. 3801. String LD
  4. OpenRisc-52-run openrisc&orpmon on ml501 board
  5. Free Pascal的IDE界面乱码解决方法
  6. Duff and Meat - CF 588A
  7. 3DMax的OFusion插件使用问题
  8. hdu2544(自己实现优先队列)
  9. c++ 计算程序运行时间
  10. 解决phpmyadmin 点击表结构时卡顿、一直加载、打不开的问题
  11. Django+Vue打造购物网站(八)
  12. HttpWebResponse Post 前端控件数据,后台如何接收?
  13. docker swarm集群搭建以及使用滚动更新
  14. day11-(cookie&&session)
  15. Redis cluster集群模式的原理
  16. centos设置中文输入法无效的解决办法
  17. 什么是 metadata (元数据)
  18. 旋转/非旋转treap的简单操作
  19. my.工坊_ZZ
  20. ADO访问Oracle数据库,连接异常(Unknown error 0x800a0e7a)

热门文章

  1. Sqlserver 增删改查----改
  2. 二、react开发环境配置与webpack入门
  3. 前端01 HTML5
  4. SpringBoot+SpringSecurity之多模块用户认证授权同步
  5. RMAN > BACKUP VALIDATE DATABASE ARCHIVELOG ALL
  6. UML概念
  7. 【TensorFlow】tf.reset_default_graph()函数
  8. UML-使用多态性和“Do It Myself”模式处理支付
  9. part9 公用图片画廊组件拆分
  10. CodeForces - 446A DZY Loves Sequences(dp)