深度学习之格式转换笔记(四):Keras(.h5)模型转化为TensorFlow(.pb)模型

简介: 本文介绍了如何使用Python脚本将Keras模型转换为TensorFlow的.pb格式模型,包括加载模型、重命名输出节点和量化等步骤,以便在TensorFlow中进行部署和推理。

环境

tensorflow-gpu 1.15 ,keras 2.3.1,cuda 10.0.0 ,cudnn 7.6.4
tensorflow和keras对应版本:https://docs.floydhub.com/guides/environments/

h5模型转pb模型

源代码:

#!/usr/bin/env python

import tensorflow as tf
from tensorflow.python.framework import graph_util
from tensorflow.python.framework import graph_io
from pathlib import Path
from absl import app
from absl import flags
from absl import logging
import keras
from keras import backend as K
from keras.models import model_from_json, model_from_yaml

K.set_learning_phase(0)
FLAGS = flags.FLAGS

flags.DEFINE_string('input_model', None, 'Path to the input model.')
flags.DEFINE_string('input_model_json', None, 'Path to the input model '
                                              'architecture in json format.')
flags.DEFINE_string('input_model_yaml', None, 'Path to the input model '
                                              'architecture in yaml format.')
flags.DEFINE_string('output_model', None, 'Path where the converted model will '
                                          'be stored.')
flags.DEFINE_boolean('save_graph_def', False,
                     'Whether to save the graphdef.pbtxt file which contains '
                     'the graph definition in ASCII format.')
flags.DEFINE_string('output_nodes_prefix', None,
                    'If set, the output nodes will be renamed to '
                    '`output_nodes_prefix`+i, where `i` will numerate the '
                    'number of of output nodes of the network.')
flags.DEFINE_boolean('quantize', False,
                     'If set, the resultant TensorFlow graph weights will be '
                     'converted from float into eight-bit equivalents. See '
                     'documentation here: '
                     'https://github.com/tensorflow/tensorflow/tree/master/tensorflow/tools/graph_transforms')
flags.DEFINE_boolean('channels_first', False,
                     'Whether channels are the first dimension of a tensor. '
                     'The default is TensorFlow behaviour where channels are '
                     'the last dimension.')
flags.DEFINE_boolean('output_meta_ckpt', False,
                     'If set to True, exports the model as .meta, .index, and '
                     '.data files, with a checkpoint file. These can be later '
                     'loaded in TensorFlow to continue training.')

flags.mark_flag_as_required('input_model')
flags.mark_flag_as_required('output_model')

def load_model(input_model_path, input_json_path=None, input_yaml_path=None):
    if not Path(input_model_path).exists():
        raise FileNotFoundError(
            'Model file `{}` does not exist.'.format(input_model_path))
    try:
        model = keras.models.load_model(input_model_path, compile=False)
        return model
    except FileNotFoundError as err:
        logging.error('Input mode file (%s) does not exist.', FLAGS.input_model)
        raise err
    except ValueError as wrong_file_err:
        if input_json_path:
            if not Path(input_json_path).exists():
                raise FileNotFoundError(
                    'Model description json file `{}` does not exist.'.format(
                        input_json_path))
            try:
                model = model_from_json(open(str(input_json_path)).read())
                model.load_weights(input_model_path)
                return model
            except Exception as err:
                logging.error("Couldn't load model from json.")
                raise err
        elif input_yaml_path:
            if not Path(input_yaml_path).exists():
                raise FileNotFoundError(
                    'Model description yaml file `{}` does not exist.'.format(
                        input_yaml_path))
            try:
                model = model_from_yaml(open(str(input_yaml_path)).read())
                model.load_weights(input_model_path)
                return model
            except Exception as err:
                logging.error("Couldn't load model from yaml.")
                raise err
        else:
            logging.error(
                'Input file specified only holds the weights, and not '
                'the model definition. Save the model using '
                'model.save(filename.h5) which will contain the network '
                'architecture as well as its weights. '
                'If the model is saved using the '
                'model.save_weights(filename) function, either '
                'input_model_json or input_model_yaml flags should be set to '
                'to import the network architecture prior to loading the '
                'weights. \n'
                'Check the keras documentation for more details '
                '(https://keras.io/getting-started/faq/)')
            raise wrong_file_err

def main(args):
    # If output_model path is relative and in cwd, make it absolute from root
    output_model = FLAGS.output_model
    if str(Path(output_model).parent) == '.':
        output_model = str((Path.cwd() / output_model))

    output_fld = Path(output_model).parent
    output_model_name = Path(output_model).name
    output_model_stem = Path(output_model).stem
    output_model_pbtxt_name = output_model_stem + '.pbtxt'

    # Create output directory if it does not exist
    Path(output_model).parent.mkdir(parents=True, exist_ok=True)

    if FLAGS.channels_first:
        K.set_image_data_format('channels_first')
    else:
        K.set_image_data_format('channels_last')

    model = load_model(FLAGS.input_model, FLAGS.input_model_json, FLAGS.input_model_yaml)

    # TODO(amirabdi): Support networks with multiple inputs
    orig_output_node_names = [node.op.name for node in model.outputs]
    if FLAGS.output_nodes_prefix:
        num_output = len(orig_output_node_names)
        pred = [None] * num_output
        converted_output_node_names = [None] * num_output

        # Create dummy tf nodes to rename output
        for i in range(num_output):
            converted_output_node_names[i] = '{}{}'.format(
                FLAGS.output_nodes_prefix, i)
            pred[i] = tf.identity(model.outputs[i],
                                  name=converted_output_node_names[i])
    else:
        converted_output_node_names = orig_output_node_names
    logging.info('Converted output node names are: %s',
                 str(converted_output_node_names))

    sess = K.get_session()
    if FLAGS.output_meta_ckpt:
        saver = tf.train.Saver()
        saver.save(sess, str(output_fld / output_model_stem))

    if FLAGS.save_graph_def:
        tf.train.write_graph(sess.graph.as_graph_def(), str(output_fld),
                             output_model_pbtxt_name, as_text=True)
        logging.info('Saved the graph definition in ascii format at %s',
                     str(Path(output_fld) / output_model_pbtxt_name))

    if FLAGS.quantize:
        from tensorflow.tools.graph_transforms import TransformGraph
        transforms = ["quantize_weights", "quantize_nodes"]
        transformed_graph_def = TransformGraph(sess.graph.as_graph_def(), [],
                                               converted_output_node_names,
                                               transforms)
        constant_graph = graph_util.convert_variables_to_constants(
            sess,
            transformed_graph_def,
            converted_output_node_names)
    else:
        constant_graph = graph_util.convert_variables_to_constants(
            sess,
            sess.graph.as_graph_def(),
            converted_output_node_names)

    graph_io.write_graph(constant_graph, str(output_fld), output_model_name,
                         as_text=False)
    logging.info('Saved the freezed graph at %s',
                 str(Path(output_fld) / output_model_name))

if __name__ == "__main__":
    app.run(main)

终端运行:python keras_to_tensorflow.py -input_model ‘D:\pycharm\End-to-end-for-chinese-plate-recognition\License-plate-recognition\cnn.h5’ -output_model 'D:\pycharm\End-to-end-for-chinese-plate-recognition\License-plate-recognition\cnn.pb

如何使用:
python keras_to_tensorflow.py
–input_model=“path/to/keras/model.h5”
–output_model=“path/to/save/model.pb”
或者
python keras_to_tensorflow.py
–input_model=“path/to/keras/model.h5”
–input_model_json=“path/to/keras/model.json”
–output_model=“path/to/save/model.pb”

目录
相关文章
|
2天前
|
机器学习/深度学习 TensorFlow 算法框架/工具
深度学习之格式转换笔记(三):keras(.hdf5)模型转TensorFlow(.pb) 转TensorRT(.uff)格式
将Keras训练好的.hdf5模型转换为TensorFlow的.pb模型,然后再转换为TensorRT支持的.uff格式,并提供了转换代码和测试步骤。
17 3
深度学习之格式转换笔记(三):keras(.hdf5)模型转TensorFlow(.pb) 转TensorRT(.uff)格式
|
2天前
|
机器学习/深度学习 TensorFlow 算法框架/工具
深度学习之格式转换笔记(二):CKPT 转换成 PB格式文件
将TensorFlow的CKPT模型格式转换为PB格式文件,包括保存模型的代码示例和将ckpt固化为pb模型的详细步骤。
11 2
深度学习之格式转换笔记(二):CKPT 转换成 PB格式文件
|
3天前
|
机器学习/深度学习 边缘计算 人工智能
探讨深度学习在图像识别中的应用及优化策略
【10月更文挑战第5天】探讨深度学习在图像识别中的应用及优化策略
14 1
|
8天前
|
机器学习/深度学习 人工智能 数据可视化
深度学习在图像识别中的应用与挑战
本文将深入探讨深度学习技术在图像识别领域的应用,并揭示其背后的原理和面临的挑战。我们将通过代码示例来展示如何利用深度学习进行图像识别,并讨论可能遇到的问题和解决方案。
33 3
|
3天前
|
机器学习/深度学习 存储 数据处理
深度学习在图像识别中的应用与挑战
【10月更文挑战第5天】 本文旨在探讨深度学习技术在图像识别领域的应用及其所面临的挑战。随着深度学习技术的飞速发展,其在图像识别中的应用日益广泛,不仅推动了相关技术的革新,也带来了新的挑战。本文首先介绍了深度学习的基本原理和常见模型,然后详细探讨了卷积神经网络(CNN)在图像识别中的具体应用,包括图像分类、目标检测等任务。接着,分析了当前深度学习在图像识别中面临的主要挑战,如数据标注问题、模型泛化能力、计算资源需求等。最后,提出了一些应对这些挑战的可能方向和策略。通过综合分析,本文希望为深度学习在图像识别领域的进一步研究和应用提供参考和启示。
|
3天前
|
机器学习/深度学习 人工智能 自然语言处理
深度学习在图像识别中的应用与挑战
【10月更文挑战第5天】本文将深入探讨深度学习技术在图像识别领域的应用和面临的挑战。我们将从基础的神经网络模型出发,逐步介绍卷积神经网络(CNN)的原理和结构,并通过代码示例展示其在图像分类任务中的实际应用。同时,我们也将讨论深度学习在图像识别中遇到的一些常见问题和解决方案,以及未来的发展方向。
14 4
|
1天前
|
机器学习/深度学习 人工智能 算法框架/工具
深度学习中的卷积神经网络(CNN)及其在图像识别中的应用
【10月更文挑战第7天】本文将深入探讨卷积神经网络(CNN)的基本原理,以及它如何在图像识别领域中大放异彩。我们将从CNN的核心组件出发,逐步解析其工作原理,并通过一个实际的代码示例,展示如何利用Python和深度学习框架实现一个简单的图像分类模型。文章旨在为初学者提供一个清晰的入门路径,同时为有经验的开发者提供一些深入理解的视角。
|
4天前
|
机器学习/深度学习 自动驾驶 算法
深度学习中的图像识别技术及其在自动驾驶中的应用
【10月更文挑战第4天】本文深入探讨了深度学习在图像识别领域的应用,并特别关注其在自动驾驶系统中的关键作用。文章首先介绍了深度学习的基本概念和工作原理,随后通过一个代码示例展示了如何利用深度学习进行图像分类。接着,文章详细讨论了图像识别技术在自动驾驶中的具体应用,包括物体检测、场景理解和决策制定等方面。最后,文章分析了当前自动驾驶技术面临的挑战和未来的发展趋势。
16 4
|
2天前
|
机器学习/深度学习 自然语言处理 搜索推荐
探索深度学习中的注意力机制及其在现代应用中的影响
探索深度学习中的注意力机制及其在现代应用中的影响
12 1
|
6天前
|
机器学习/深度学习 编解码 边缘计算
深度学习在图像处理中的应用与展望##
本文旨在探讨深度学习技术在图像处理领域的应用及其未来发展趋势。通过分析卷积神经网络(CNN)等关键技术,展示了深度学习如何提升图像识别、分类和生成等任务的性能。同时,本文也讨论了当前面临的挑战和未来的研究方向,为相关领域的研究和实践提供参考。 ##

热门文章

最新文章