精华内容
下载资源
问答
  • Tensorflow h5转pb

    2021-07-03 16:32:27
    Tensorflow 2 h5转pb tensorflow 2中h5转pb比较简单,加载h5模型后,使用save_model即可 from tensorflow.keras import models models.load_model('model.h5') models.save_model(model, pb_outpath) 但因为tf2...

    Tensorflow 2 h5转pb

    tensorflow 2中h5转pb比较简单,加载h5模型后,使用save_model即可

    from tensorflow.keras import models
    
    models.load_model('model.h5')
    models.save_model(model, pb_outpath)

    但因为tf2推荐使用saved_model格式,实际保存的是saved_model,即1个pb文件和两个文件夹。

    Tensorflow 1 h5转pb

    这里使用的是keras,首先加载模型,查看输入输出

    from keras.models import load_model
    model = load_model('./model/keras_model.h5')
    print(model.outputs)
    # [<tf.Tensor 'dense_2/Softmax:0' shape=(?, 10) dtype=float32>]
    print(model.inputs)
    # [<tf.Tensor 'conv2d_1_input:0' shape=(?, 28, 28, 1) dtype=float32>]

    获取模型序列化静态计算图

    from keras import backend as K
    import tensorflow as tf
    
    def freeze_session(session, keep_var_names=None, output_names=None, clear_devices=True):
        """
        Freezes the state of a session into a pruned computation graph.
    
        Creates a new computation graph where variable nodes are replaced by
        constants taking their current value in the session. The new graph will be
        pruned so subgraphs that are not necessary to compute the requested
        outputs are removed.
        @param session The TensorFlow session to be frozen.
        @param keep_var_names A list of variable names that should not be frozen,
                              or None to freeze all the variables in the graph.
        @param output_names Names of the relevant graph outputs.
        @param clear_devices Remove the device directives from the graph for better portability.
        @return The frozen graph definition.
        """
        from tensorflow.python.framework.graph_util import convert_variables_to_constants
        graph = session.graph
        with 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()]
            # Graph -> GraphDef ProtoBuf
            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_graph
    
    
    frozen_graph = freeze_session(K.get_session(),
                                  output_names=[out.op.name for out in model.outputs])

    将模型保存出二进制pb文件

    # Save to ./model/tf_model.pb
    tf.train.write_graph(frozen_graph, "model", "tf_model.pb", as_text=False)

    使用pb模型的话,首先加载pb文件中的计算图

    import tensorflow as tf
    from tensorflow.python.platform import gfile
    
    f = gfile.FastGFile("./model/tf_model.pb", 'rb')
    graph_def = tf.GraphDef()
    # Parses a serialized binary message into the current message.
    graph_def.ParseFromString(f.read())
    f.close()
    
    sess.graph.as_default()
    # Import a serialized TensorFlow `GraphDef` protocol buffer
    # and place into the current default `Graph`.
    tf.import_graph_def(graph_def)

    指定输入输出,做预测

    softmax_tensor = sess.graph.get_tensor_by_name('import/dense_2/Softmax:0')
    predictions = sess.run(softmax_tensor, {'import/conv2d_1_input:0': x_test[:20]})

    参考:如何将训练有素的 Keras 模型转换为单个 TensorFlow .pb 文件,并做出预测|直学 (dlology.com)

    展开全文
  • Tensorflow① 模型转换 ckpt转pb h5转pb

    万次阅读 热门讨论 2018-11-16 11:39:55
    此篇博客重在总结Tensorflow,Keras模型训练的模型文件转换为pb结构的方式,节省寻找转换工具的时间。 1. Tensorflow ckpt模型转换pb模型 我们在Tensorflow中训练出来的模型一般是ckpt格式的,一个ckpt文件对...

    此篇博客重在总结Tensorflow,Keras模型训练的模型文件转换为pb结构的方式,节省寻找转换工具的时间。

    1. Tensorflow ckpt模型转换pb模型

    我们在Tensorflow中训练出来的模型一般是ckpt格式的,一个ckpt文件对应有xxx.ckpt.dataxxx.ckpt.metaxxx.ckpt.index三个内容。

    而在生产环境中,一般C++只能加载pb的模型,即将ckpt的结构3合1,一个模型只对应一个pb(当然甚至可能多个模型也能合成为一个pb,这里不进行展开)。

    废话不说了,上代码

    def freeze_graph(input_checkpoint, output_graph):
        '''
    
        :param input_checkpoint: xxx.ckpt(千万不要加后面的xxx.ckpt.data这种,到ckpt就行了!)
        :param output_graph: PB模型保存路径
        :return:
        '''
        # checkpoint = tf.train.get_checkpoint_state(model_folder) #检查目录下ckpt文件状态是否可用
        # input_checkpoint = checkpoint.model_checkpoint_path #得ckpt文件路径
    
        # 指定输出的节点名称,该节点名称必须是原模型中存在的节点
        output_node_names = "softmax" # 模型输入节点,根据情况自定义
        saver = tf.train.import_meta_graph(input_checkpoint + '.meta', clear_devices=True)
        graph = tf.get_default_graph() # 获得默认的图
        input_graph_def = graph.as_graph_def()  # 返回一个序列化的图代表当前的图
    
        with tf.Session() as sess:
            saver.restore(sess, input_checkpoint) # 恢复图并得到数据
            output_graph_def = graph_util.convert_variables_to_constants(  # 模型持久化,将变量值固定
                sess=sess,
                input_graph_def=input_graph_def,# 等于:sess.graph_def
                output_node_names=output_node_names.split(","))# 如果有多个输出节点,以逗号隔开
    
            with tf.gfile.GFile(output_graph, "wb") as f: #保存模型
                f.write(output_graph_def.SerializeToString()) #序列化输出
            print("%d ops in the final graph." % len(output_graph_def.node)) #得到当前图有几个操作节点
    

    用法

    input_checkpoint = 'xxx.ckpt'
    out_graph = 'froze_xxx.pb'
    freeze_graph(input_checkpoint, out_graph) 
    

    2. Keras h5模型转换pb模型

    现在keras和Tensorflow的集成也越来越紧密了,用户可以通过tf.contrib.keras在tensorflow中引入keras使用,即keras和tensorflow相互耦合,而非之前那样,只是tensorflow的高层封装。

    因为keras的很多ops封装的很简单,所以现在一般用keras搭模型的人很多,那么问题来了,如果想在生产环境中使用keras框架产生的hdf5格式的模型文件,也需要将其转换为pb格式,怎么做呢?Let’s roll it!

    def freeze_session(session, keep_var_names=None, output_names=None, clear_devices=True):
        """
        Freezes the state of a session into a prunned computation graph.
    
        Creates a new computation graph where variable nodes are replaced by
        constants taking their current value in the session. The new graph will be
        prunned so subgraphs that are not neccesary to compute the requested
        outputs are removed.
        @param session The TensorFlow session to be frozen.
        @param keep_var_names A list of variable names that should not be frozen,
                              or None to freeze all the variables in the graph.
        @param output_names Names of the relevant graph outputs.
        @param clear_devices Remove the device directives from the graph for better portability.
        @return The frozen graph definition.
        """
        from tensorflow.python.framework.graph_util import convert_variables_to_constants
        graph = session.graph
        with 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_graph
    
    
    input_fld = sys.path[0]
    weight_file = 'vgg16_without_dropout.h5'
    output_graph_name = 'vgg16_without_dropout.pb'
    
    output_fld = input_fld + '/tensorflow_model/'
    if not os.path.isdir(output_fld):
        os.mkdir(output_fld)
    weight_file_path = osp.join(input_fld, weight_file)
    
    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(K.get_session(), output_names=[net_model.output.op.name])
    
    from tensorflow.python.framework import graph_io
    
    graph_io.write_graph(frozen_graph, output_fld, output_graph_name, as_text=False)
    
    print('saved the constant graph (ready for inference) at: ', osp.join(output_fld, output_graph_name))
    

    3. 参考资料

    [1] Eileng: keras模型保存为tensorflow的二进制模型
    [2] 嘿芝麻:tensorflow框架.ckpt .pb模型节点tensor_name打印及ckpt模型转.pb模型

    展开全文
  • h5 pb文件

    2020-05-07 10:08:30
    tf.io.write_graph(graph_or_graph_def=frozen_func.graph, logdir="", name="frozen_graph.pb", as_text=False) 完整代码: # Copyright 2020 chenli Authors. All Rights Reserved. import tensorflow as tf ...

    关键代码,这里的模型为tf.keras 模型:

    from tensorflow.python.framework.convert_to_constants import convert_variables_to_constants_v2
    
        full_model = tf.function(lambda x: model(x))
        full_model = full_model.get_concrete_function(
            tf.TensorSpec(model.inputs[0].shape, model.inputs[0].dtype))
    
        # Get frozen ConcreteFunction
        frozen_func = convert_variables_to_constants_v2(full_model)
        frozen_func.graph.as_graph_def()
        tf.io.write_graph(graph_or_graph_def=frozen_func.graph,
                          logdir="",
                          name="frozen_graph.pb",
                          as_text=False)

    PS:建议在tensorflow1.14版本以上进行转换。

    完整代码:

    # Copyright 2020 chenli Authors. All Rights Reserved.
    import tensorflow as tf
    import os
    from mobilenetv3_factory import build_mobilenetv3
    
    
    def mobilenetv3_creat(num_classes=2, img_size=128):
        """模型创建
        :param:
        num_classes:类别数
        img_size(int):图像大小
        :return:
        model:模型
        """
    
        # read mobilenetv3 model
        model = build_mobilenetv3(
            "small",
            input_shape=(img_size, img_size, 3),
            num_classes=num_classes,
            width_multiplier=1.0,
            l2_reg=1e-5,
        )
        return model
    
    
    def mobilenetv3_load_weight(model, model_path="mobilenetv3_small_10.h5"):
        """"加载权重
        :param:
        model:模型
        model_path(str):模型权重路径
        :return:
        model:模型
        """
        model.load_weights(model_path)
        return model
    
    
    if __name__ == "__main__":
        tf.enable_eager_execution()
        # tf.keras.set_learning_phase(0)
        classes = ['ClientFace', 'ImposterFace']
        num_classes = len(classes)
        img_size = 128
        model_path = "mobilenetv3_small_10.h5"
        model = mobilenetv3_creat(num_classes=num_classes, img_size=img_size)
    
        model = mobilenetv3_load_weight(model, model_path=model_path)
    
        from tensorflow.python.framework.convert_to_constants import convert_variables_to_constants_v2
    
        full_model = tf.function(lambda x: model(x))
        full_model = full_model.get_concrete_function(
            tf.TensorSpec(model.inputs[0].shape, model.inputs[0].dtype))
    
        # Get frozen ConcreteFunction
        frozen_func = convert_variables_to_constants_v2(full_model)
        frozen_func.graph.as_graph_def()
        tf.io.write_graph(graph_or_graph_def=frozen_func.graph,
                          logdir="",
                          name="frozen_graph.pb",
                          as_text=False)
    
    

     

    展开全文
  • https://github.com/nistarlwc/keras-yolo3-convert2pb
  • keras中的.h5转pb代码

    千次阅读 2019-05-17 15:16:40
    将keras的.h5的模型文件,转换成TensorFlow的pb文件 """ # ========================================================== from keras.models import load_model import tensorflow as tf import os fr...

     

    #*-coding:utf-8-*
    
    """
    将keras的.h5的模型文件,转换成TensorFlow的pb文件
    """
    # ==========================================================
    
    from keras.models import load_model
    import tensorflow as tf
    import os
    from keras import backend
    from keras.applications.mobilenetv2 import MobileNetV2
    from keras.layers import Input
    from keras.preprocessing import image
    from keras.applications.mobilenetv2 import preprocess_input, decode_predictions
    from keras.applications.inception_resnet_v2 import InceptionResNetV2
    
    
    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_path = '../models/'
        weight_file = 'inception_resnet_v2_weights_tf_dim_ordering_tf_kernels.h5'
        #weight_file = 'mobilenet_v2_weights_tf_dim_ordering_tf_kernels_1.4_224.h5'
        weight_file_path = os.path.join(input_path, weight_file)
        output_graph_name = weight_file[:-3] + '.pb'
    
        #  pb模型文件输出输出路径
        output_dir = input_path
    
        #  加载模型
        h5_model = 0
    
        if weight_file.find("mobile")!=-1:
            input_tensor = Input(shape=(224, 224, 3))  # or you could put (None, None, 3) for shape.
            h5_model = MobileNetV2(input_tensor=input_tensor, alpha=1.4, include_top=True,weights=input_path+weight_file)
        elif weight_file.find("inception_resnet")!=-1:
            h5_model = InceptionResNetV2("imagenet",include_top=True,)
    
    
        h5_model.summary()
        h5_to_pb(h5_model, output_dir=output_dir, model_name=output_graph_name)
        print('Finished')
    
    

     

    展开全文
  • import tensorflow as tf import tensorflow_hub as hub from tensorflow.python.framework.convert_to_constants import convert_variables...def h5_to_pb(h5_save_path): model = tf.keras.models.load_model(h5_.
  • 注意:os.environ[‘TF_KERAS’] = ‘1’ 放在bert4keras,keras...1、保存pb格式 import numpy as np import os from collections import Counter os.environ['TF_KERAS'] = '1' from bert4keras.backend import kera
  • h5文件转pb文件

    千次阅读 2019-05-12 17:48:50
    #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 = './' weight_file ...
  • h5模型转pb转tflite实现及报错解决     这里我已Mask R-CNN训练出来的模型为例,我的h5文件不保存模型结构,我的代码有转为带结构的h5文件。话不多说,直接上代码。 def save_model(path): """ 将训练的仅保存...
  • from keras.models import load_model import tensorflow as tf import os import os.path as osp from keras import ...def h5_to_pb(h5_model,output_dir,model_name,out_prefix = "yourname_",log_tensorbo...
  • .h5 To Pb

    2019-10-18 15:26:29
    以下代码实现了把.h5文件转换成pb的过程 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 = '/home/simon/...
  • 前言 深度学习模型开发首选Keras,模型搭建简单快速。...h5转pb格式 方法一 Keras模型保存时使用 save() 函数保存,转换代码如下: from keras.models import load_model import tensorflow as t...
  • 本文总结了keras生成的h5模型文件转换成pb文件的方法,并用tensorflow框架成功加载由h5文件成的pb文件进行命名实体识别任务预测新句子中的实体。欢迎转载,转载请注明出处。
  • yolov3.pb文件(keras) 我是先的weight,再的.pbweights参考https://github.com/amir-abdi/keras_to_tensorflow.git和博客https://blog.csdn.net/python_pycharm/article/details/106804233,.pb参考...
  • .h5转.pb的两种方式: 方法一: Keras的.h5模型成tensorflow的.pb格式模型,方便后期的前端部署。直接上代码 from keras.models import Model from keras.layers import Dense, Dropout from ...
  • 该方法只适用于通过save_model保存的keras模型文件(.h5),不适用于通过save_weights保存的keras模型文件,直接上代码。 import keras from keras.models import load_model import tensorflow as tf import os....
  • h5模型文件转换成pb模型文件

    千次阅读 2019-04-10 20:36:00
      本文主要记录Keras训练得到的.h5模型文件转换成TensorFlow的.pb文件 #*-coding:utf-8-* """ 将keras的.h5的模型文件,转换成TensorFlow的pb文件 """ # =======================================================...

空空如也

空空如也

1 2 3 4 5 ... 20
收藏数 3,791
精华内容 1,516
关键字:

h5转pb