博客
关于我
强烈建议你试试无所不能的chatGPT,快点击我
将keras的h5模型转换为tensorflow的pb模型
阅读量:4261 次
发布时间:2019-05-26

本文共 2039 字,大约阅读时间需要 6 分钟。

背景:目前keras框架使用简单,很容易上手,深得广大算法工程师的喜爱,但是当部署到客户端时,可能会出现各种各样的bug,甚至不支持使用keras,本文来解决的是将keras的h5模型转换为客户端常用的tensorflow的pb模型并使用tensorflow加载pb模型。

h5_to_pb.pyfrom keras.models import load_modelimport tensorflow as tfimport os import os.path as ospfrom 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.pyimport tensorflow as tffrom tensorflow.python.platform import gfiledef 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)

 

转载地址:http://lqlei.baihongyu.com/

你可能感兴趣的文章
IPV6:移动光猫吉比特GM228-S 桥接+IPV6教程
查看>>
Rect类的使用结果
查看>>
堆排序代码实现
查看>>
图的邻接矩阵代码实现
查看>>
图的邻接表代码实现
查看>>
最小生成树Prim算法
查看>>
Listview中某个item需要有倒计时的方案
查看>>
Activity ,Window ,WindowManager之间的关系
查看>>
org.xmlpull.v1.XmlPullParserException: preconditon: START_TAG
查看>>
从反编译微信看到的资源文件保护
查看>>
Mac上下载编译Android 6.0源码详细记录
查看>>
Activity与Fragment通信 多接口实现优化
查看>>
我的音乐播放器
查看>>
使用Jadx反编译apk
查看>>
BUG:记MediaBrowserService的onLoadChildren不执行
查看>>
QQ音乐API整理
查看>>
DrawerLayout侧滑高斯模糊实现
查看>>
Aspectj简单使用(一)
查看>>
视频 api 收集
查看>>
内存泄露:AccessibilityManager
查看>>