MxNet 模型转Tensorflow pb模型

用mmdnn实现模型转换

参考链接:https://www.twblogs.net/a/5ca4cadbbd9eee5b1a0713af

  1. 安装mmdnn

    pip install mmdnn
  2. 准备好mxnet模型的.json文件和.params文件, 以InsightFace MxNet r50为例        https://github.com/deepinsight/insightface
  3. 用mmdnn运行命令行

    python -m mmdnn.conversion._script.convertToIR -f mxnet -n model-symbol.json -w model-0000.params -d resnet50 --inputShape 3,112,112 

     会生成resnet50.json(可视化文件) resnet50.npy(权重参数) resnet50.pb(网络结构)三个文件。

  4. 用mmdnn运行命令行

    python -m mmdnn.conversion._script.IRToCode -f tensorflow --IRModelPath resnet50.pb --IRWeightPath resnet50.npy --dstModelPath tf_resnet50.py 

     生成tf_resnet50.py文件,可以调用tf_resnet50.py中的KitModel函数加载npy权重参数重新生成原网络框架。

  5. 打开tf_resnet.py文件,修改load_weights()中的代码 (tensorflow=1.14.0报错) 
     try:
            weights_dict = np.load(weight_file).item()
        except:
            weights_dict = np.load(weight_file, encoding=‘bytes‘).item()

    改为

     try:
            weights_dict = np.load(weight_file, allow_pickle=True).item()
    except:
            weights_dict = np.load(weight_file, allow_pickle=True, encoding=‘bytes‘).item()
  6. 基于resnet50.npy和tf_resnet50.py文??件,固化参数,生成PB文件:
    import tensorflow as tf
    import tf_resnet50 as tf_fun
    def netWork():
        model=tf_fun.KitModel("./resnet50.npy")
        return model
    def freeze_graph(output_graph):
        output_node_names = "output"
        data,fc1=netWork()
        fc1=tf.identity(fc1,name="output")
    
        graph = tf.get_default_graph()  # 獲得默認的圖
        input_graph_def = graph.as_graph_def()  # 返回一個序列化的圖代表當前的圖
        init = tf.global_variables_initializer()
        with tf.Session() as sess:
            sess.run(init)
            output_graph_def = tf.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())  # 序列化輸出
    
    if __name__ == ‘__main__‘:
        freeze_graph("frozen_insightface_r50.pb")
        print("finish!")
  7. 采用tensorflow的post-train quantization离线量化方法(有一定的精度损失)转换成tflite模型,从而完成端侧的模型部署:

    import tensorflow as tf
    
    convert=tf.lite.TFLiteConverter.from_frozen_graph("frozen_insightface_r50.pb",input_arrays=["data"],output_arrays=["output"],
                                                      input_shapes={"data":[1,112,112,3]})
    convert.post_training_quantize=True
    tflite_model=convert.convert()
    open("quantized_insightface_r50.tflite","wb").write(tflite_model)
    print("finish!")

原文地址:https://www.cnblogs.com/qiangz/p/11134240.html

时间: 2024-08-29 20:12:37

MxNet 模型转Tensorflow pb模型的相关文章

tensorflow机器学习模型的跨平台上线

在用PMML实现机器学习模型的跨平台上线中,我们讨论了使用PMML文件来实现跨平台模型上线的方法,这个方法当然也适用于tensorflow生成的模型,但是由于tensorflow模型往往较大,使用无法优化的PMML文件大多数时候很笨拙,因此本文我们专门讨论下tensorflow机器学习模型的跨平台上线的方法. 1. tensorflow模型的跨平台上线的备选方案 tensorflow模型的跨平台上线的备选方案一般有三种:即PMML方式,tensorflow serving方式,以及跨语言API方

Tensorflow Learning1 模型的保存和恢复

CKPT->pb Demo 解析 tensor name 和 node name 的区别 Pb 的恢复 CKPT->pb tensorflow的模型保存有两种形式: 1. ckpt:可以恢复图和变量,继续做训练 2. pb : 将图序列化,变量成为固定的值,,只可以做inference:不能继续训练 Demo 1 def freeze_graph(input_checkpoint,output_graph): 2 3 ''' 4 :param input_checkpoint: 5 :para

TensorFlow 图像分类模型 inception_resnet_v2 模型导出、冻结与使用

1. 背景 作为一名深度学习萌新,项目突然需要使用图像分类模型去作分类,因此找到了TensorFlow的模型库,使用它的框架进行训练和后续的操作,项目地址:https://github.com/tensorflow/models/tree/master/research/slim. 在使用真正的数据集之前,我首先使用的是它提供的flowers的数据集,用的模型是inception_resnet_v2,因为top-5 Accuracy比较高嘛. 然后我安装flowers的目录结构,将我的数据按照类

TensorFlow计算模型—计算图

TensorFlow是一个通过计算图的形式来表述计算的编程系统.其中的Tnesor,代表它的数据结构,而Flow代表它的计算模型.TensorFlow中的每一个计算都是计算图上的一个节点,而节点之间的线描述了计算之间的依赖关系. 在TensorFlow程序中,系统会自动维护一个默认的计算图,通过tf.get_default_gragh函数可以获取当前默认的计算图. 除了默认的计算图,TensorFlow也支持通过tf.Graph函数来生成新的计算图.不同的计算图上的张量和运算不会共享.如下示例:

学习笔记CB014:TensorFlow seq2seq模型步步进阶

神经网络.<Make Your Own Neural Network>,用非常通俗易懂描述讲解人工神经网络原理用代码实现,试验效果非常好. 循环神经网络和LSTM.Christopher Olah http://colah.github.io/posts/2015-08-Understanding-LSTMs/ . seq2seq模型基于循环神经网络序列到序列模型,语言翻译.自动问答等序列到序列场景,都可用seq2seq模型,用seq2seq实现聊天机器人的原理 http://suriyade

(转)Darknet模型与Tensorflow模型相互转换

目前darknet框架下的模型训练都是在C环境下训练的,难免较为晦涩,如果能将模型转换到Tensorflow环境下完成模型的训练,在将训练好的权重转为Darknet可以识别的权重部署到实际应用中.这样就可以将算法的训练和实际部署分开! 1.将Darknet框架下的.cfg与.weights 转为Tensorflow框架下的.cpkt模型 先clone这个项目,用于darknet模型转tensorflow https://github.com/Linzmin1927/DW2TFcd 到DW2TF目

padding标准盒模型和怪异盒子模型

我们都知道padding是为块级元素设置内边距 但是在使用过程中,我们却会遇到一些问题.padding的标准盒模型和怪异盒模型 padding盒子模型 我们通过demo来讲这个问题,用文字干讲第一没意思,第二讲不明白 标准盒模型: 我们先摆出HTML和CSS代码: 1 <div class="shoebox"> <!--此div模仿鞋子的鞋盒--> 2 <div class="shoes"> <!--此div模仿鞋子--&g

ThinkPHP 学习笔记 ( 四 ) 数据库操作之关联模型 ( RelationMondel ) 和高级模型 ( AdvModel )

一.关联模型 ( RelationMondel ) 1.数据查询 ① HAS_ONE 查询 创建两张数据表评论表和文章表: tpk_comment , tpk_article .评论和文章的对应关系为,一条评论 id 对应一篇文章,为 ONE_TO_ONE 关系 ( 一对一 ).评论表的结构为: 其中 aid 字段与文章表的 id 字段对应.打开自定义模型 ArticleModel,让模型继承于 RelationModel,然后定义成员属性 $_link,代码: ArticleModel.cla

判别式模型和产生式模型 (discriminative model and generative m

最经典的莫过于 Andrew Ng在NIPS2001年有一篇专门比较判别模型和产生式模型的文章: On Discrimitive vs. Generative classifiers: A comparision of logistic regression and naive Bayes (http://robotics.stanford.edu/~ang/papers/nips01-discriminativegenerative.pdf) 转: 判别式模型和产生式模型 (discrimin