美文网首页
tensorflow 模型转换,部署到移动端

tensorflow 模型转换,部署到移动端

作者: 滴答大 | 来源:发表于2020-11-25 17:23 被阅读0次

    1、生成模型文件,四个,功能如下:

    image.png

    具体生成代码,新建saveModel.py

    import tensorflow.compat.v1 as tf
    tf.disable_v2_behavior()
    import shutil
    import os.path
    
    
    MODEL_DIR = "/Users/qing/Desktop/code/tensorflow_classification/Test6_mobilenet/product_model/"
    MODEL_NAME = "model.ckpt"
    
    
    input_holder = tf.placeholder(tf.float32, shape=[1], name="input_holder")  # 输入占位符,并指定名字,后续模型读取可能会用的
    W1 = tf.Variable(tf.constant(5.0, shape=[1]), name="W1")
    B1 = tf.Variable(tf.constant(1.0, shape=[1]), name="B1")
    _y = (input_holder * W1) + B1
    predictions = tf.add(_y, 50, name="predictions")  # 输出节点名字,后续模型读取会用到,比50大返回true,否则返回false
    
    init = tf.global_variables_initializer()
    saver = tf.train.Saver()  # 声明saver用于保存模型
    
    with tf.Session() as sess:
        sess.run(init)
        print("predictions : ")
        sess.run(predictions, feed_dict={input_holder: [10.0]}) # 输入一个数据测试一下
        saver.save(sess, os.path.join(MODEL_DIR, MODEL_NAME))  # 模型保存
        print("%d ops in the final graph." % len(tf.get_default_graph().as_graph_def().node))  # 得到当前图有几个操作节点
    

    我跑这段代码出错了,AttributeError: module 'tensorflow' has no attribute 'placeholder',说明你用的是tf2.
    解决: 把import tensorflow as tf 改成

     import tensorflow.compat.v1 as tf
    tf.disable_v2_behavior()
    

    结果:

    predictions : 
    27 ops in the final graph.
    

    ckpt模型持久化使用起来非常简单,只需要我们声明一个tf.train.Saver,然后调用save()函数,将会话模型保存到指定的目录。执行代码结果,会在我们指定模型目录下出现4个文件

    Xnip2020-11-25_17-05-02.jpg

    2、ckpt转Pb

    新建ckpbTopb.py

    # coding=UTF-8
    import tensorflow.compat.v1 as tf
    tf.disable_v2_behavior()
    import shutil
    import os.path
    from tensorflow.python.framework import graph_util
    
    #最终pb 文件的位置
    MODEL_DIR = "/Users/qing/Desktop/code/tensorflow_classification/Test6_mobilenet/product_model/"
    #最终pb 文件的名称
    MODEL_NAME = "saved_model.pb"
    
    # output_graph = "model/pb/add_model.pb"
    
    # 下面的过程你可以替换成CNN、RNN等你想做的训练过程,这里只是简单的一个计算公式
    input_holder = tf.placeholder(tf.float32, shape=[1], name="input_holder")
    W1 = tf.Variable(tf.constant(5.0, shape=[1]), name="W1")
    B1 = tf.Variable(tf.constant(1.0, shape=[1]), name="B1")
    _y = (input_holder * W1) + B1
    predictions = tf.add(_y, 50, name="predictions")
    init = tf.global_variables_initializer()
    
    with tf.Session() as sess:
        sess.run(init)
        print ("predictions : ")
        sess.run(predictions, feed_dict={input_holder: [10.0]})
        graph_def = tf.get_default_graph().as_graph_def()  # 得到当前的图的 GraphDef 部分,
        # 通过这个部分就可以完成重输入层到
        # 输出层的计算过程
    
        output_graph_def = graph_util.convert_variables_to_constants(  # 模型持久化,将变量值固定
            sess,
            graph_def,
            ["predictions"]  # 需要保存节点的名字
        )
        with tf.gfile.GFile(os.path.join(MODEL_DIR, MODEL_NAME), "wb") as f:  # 保存模型
            f.write(output_graph_def.SerializeToString())  # 序列化输出
        print("%d ops in the final graph." % len(output_graph_def.node))
        print(predictions)
    
    # for op in tf.get_default_graph().get_operations(): 打印模型节点信息
    #     print (op.name)
    
    

    结果


    Xnip2020-11-26_16-42-57.jpg

    3、 pb 转tflite

    新建pbToTflite.py

    import tensorflow as tf
    
    # 把pb文件路径改成自己的pb文件路径即可
    path="/Users/qing/Desktop/code/tensorflow_classification/Test6_mobilenet/product_model/model.pb"        #pb文件位置和文件名
    
    # 如果是不知道自己的模型的输入输出节点,建议用tensorboard做可视化查看计算图,计算图里有输入输出的节点名称
    inputs=["input_holder"]               #模型文件的输入节点名称
    outputs=["predictions"]            #模型文件的输出节点名称
    # 转换pb模型到tflite模型
    converter = tf.lite.TFLiteConverter.from_frozen_graph(path, inputs, outputs)
    converter.post_training_quantize = True
    tflite_model = converter.convert()
    # yolov3-tiny_160000.tflite这里改成自己想要保存tflite模型的地址即可
    open("model_tflite.tflite", "wb").write(tflite_model)
    
    

    报错


    Xnip2020-11-26_17-08-52.jpg

    原因是tensorflow 2 不兼容2.0以下的版本

    之后尝试2.0的方法,仍旧不成功

     import tensorflow as tf
    
    saved_model_dir = './product_model/'
     converter = tf.lite.TFLiteConverter.from_saved_model(saved_model_dir)
    converter.optimizations = ["DEFAULT"]
     converter.post_training_quantize = True  # 就这个行
     tflite_model = converter.convert()
     open("model_tflite.tflite", "wb").write(tflite_model)
    
    

    解决方式 安装python2.7,tensorflow1.13.1,具体见另一篇:
    https://www.jianshu.com/p/aca6d037d783

    部署完tensorflow1.13.1,在pycharm 运行以下代码

    # encoding: utf-8
    import tensorflow as tf
    
    # 把pb文件路径改成自己的pb文件路径即可
    path="/Users/qing/Desktop/code/tensorflow_classification/Test6_mobilenet/product_model/saved_model.pb"        #pb文件位置和文件名
    
    # 如果是不知道自己的模型的输入输出节点,建议用tensorboard做可视化查看计算图,计算图里有输入输出的节点名称
    inputs=["input_holder"]               #模型文件的输入节点名称
    outputs=["predictions"]            #模型文件的输出节点名称
    # 转换pb模型到tflite模型
    converter = tf.lite.TFLiteConverter.from_frozen_graph(path, inputs, outputs)
    converter.post_training_quantize = True
    tflite_model = converter.convert()
    # model_tflite.tflite这里改成自己想要保存tflite模型的地址即可
    open("model_tflite.tflite", "wb").write(tflite_model)
    
    
    

    结果如下,终于生成tflite模型:


    Xnip2020-11-26_17-34-05.jpg

    4、部署到移动端

    相关文章

      网友评论

          本文标题:tensorflow 模型转换,部署到移动端

          本文链接:https://www.haomeiwen.com/subject/vlvniktx.html