在深度学习的模型部署过程中,需要将模型保存成二进制的pb模型,有利于模型快速加载。
本文记载了一种h5模型转换成pb模型的方法。
复制代码
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67#*-coding:utf-8-* # 可以成功转换h5模型到pb模型 """ 将keras的.h5的模型文件,转换成TensorFlow的pb文件 """ # ========================================================== from keras.models import load_model import tensorflow as tf import os from keras import backend def h5_to_pb(h5_model, output_dir, model_name, out_prefix="output_", log_tensorboard=True): """.h5模型文件转换成pb模型文件 Argument: h5_model: str .h5模型文件 output_dir: str pb模型文件保存路径 model_name: str pb模型文件名称 out_prefix: str 根据训练,需要修改 log_tensorboard: bool 是否生成日志文件 Return: pb模型文件 """ if os.path.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 = backend.get_session() from tensorflow.python.framework import graph_util, graph_io # 写入pb模型文件 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(os.path.join(output_dir, model_name), output_dir) if __name__ == '__main__': # .h模型文件路径参数 # input_fld = 'C:/Users/song_/Desktop/helme-detector/helmet-detector-recognizer/goods-train/' # weight_file = 'yolov3.h5' # output_graph_name = 'yolov3.pb' input_path = 'C:/Users/song_/Desktop/goods-train/' weight_file = 'yolov3.h5' weight_file_path = os.path.join(input_path, weight_file) output_graph_name = weight_file[:-3] + '.pb' # pb模型文件输出输出路径 output_dir = os.path.join(os.getcwd(), r"C:Userssong_Desktopgoods-traintensorflow_model") # 加载模型 h5_model = load_model(weight_file_path) h5_to_pb(h5_model, output_dir=output_dir, model_name=output_graph_name) print('Finished')
转载于:https://www.cnblogs.com/chenzhen0530/p/10685944.html
最后
以上就是害怕钢笔最近收集整理的关于keras的h5模型转换成pb模型的方法的全部内容,更多相关keras内容请搜索靠谱客的其他文章。
本图文内容来源于网友提供,作为学习参考使用,或来自网络收集整理,版权属于原作者所有。
发表评论 取消回复