tflite模型的生成

摘要:
由于IOSApp需要使用训练的tensorflow模型进行物体检测,因此该过程被记录下来以备不时之需。这种效率的部分原因是在存储模型时使用了特殊格式。TensorFlow模型必须转换为此格式,才能由TensorFlowLite使用。它将模型常数从全精度浮点数(32位)量化为降低精度的浮点数据类型。

由于IOS App需要使用已训练的tensorflow模型进行物体检测,特将此过程记录下来已备不时之需。

一、tflite是什么

TensorFlow Lite 的设计旨在在各种设备上高效执行模型。这种高效部分源于在存储模型时,采用了一种特殊的格式。TensorFlow 模型在能被 TensorFlow Lite 使用前,必须转换成这种格式。

 tflite模型的生成第1张

由上图可知:

tflite是从训练的模型转换而来的;

tflite是为了在App设备上使用;

二、从训练结果到tflite

1、ckpt训练模型说明

 tflite模型的生成第2张

训练过程中产生的文件说明:

Checkpoint——

 tflite模型的生成第3张

保留最近几次的训练结果的索引

ckpt.data——

保存模型的中参数的值

ckpt.index——

保存模型中参数的名称和维度,相当于将模型中的参数名称和参数值关联起来

ckpt.meta——

保存计算图

2、ckpt转tflite pb模型

通过/models/research/object_detection/export_tflite_ssd_graph.py得到tflite_graph.pb模型,参数与export_inference_graph.py类似

 tflite模型的生成第4张

3、tflite pb转tflite

(1)直接转换

def convertToLite_normal():
    graph_def_file=r'E:AI...	flite_graph.pb';
    input_arrays=["normalized_input_image_tensor"]
    output_arrays=['TFLite_Detection_PostProcess','TFLite_Detection_PostProcess:1','TFLite_Detection_PostProcess:2','TFLite_Detection_PostProcess:3']
    input_tensor={"normalized_input_image_tensor":[1,300,300,3]}

    converter = tf.lite.TFLiteConverter.from_frozen_graph(graph_def_file, input_arrays, output_arrays,input_tensor)
    converter.allow_custom_ops=True
    tflite_model = converter.convert()
    open(r"E:AI...bc_normal.tflite", "wb").write(tflite_model)

(2)float16量化

训练后的float16量化减少了TensorFlow Lite模型的尺寸(高达50%),同时牺牲了很少的精度。它量化模型常量(如权重和偏差值)从全精度浮点数(32位)到降低精度浮点数数据类型(IEEE FP16)。

def convertToLite_fp16():
    # 接着实现对tflite_graph.pb模型的fp16量
    # 参考:https://zhuanlan.zhihu.com/p/90690452
    input_arrays = ["normalized_input_image_tensor"]
    output_arrays = ['TFLite_Detection_PostProcess', 'TFLite_Detection_PostProcess:1', 'TFLite_Detection_PostProcess:2',
                     'TFLite_Detection_PostProcess:3']
    input_tensor = {"normalized_input_image_tensor": [1, 300, 300, 3]}

    converter = tf.lite.TFLiteConverter.from_frozen_graph(r'E:AI...	flite_graph.pb', input_arrays, output_arrays, input_tensor)
    converter.target_ops = [tf.lite.OpsSet.TFLITE_BUILTINS, tf.lite.OpsSet.SELECT_TF_OPS]
    converter.allow_custom_ops = True
    converter.optimizations = [tf.lite.Optimize.DEFAULT]
    converter.target_spec.supported_types = [tf.lite.constants.FLOAT16]

    # converter.post_training_quantize=True
    tflite_fp16_model = converter.convert()
    # open("car_fp16.tflite", "wb").write(tflite_fp16_model)
    open(r"E:AI...bc_fp16.tflite", "wb").write(tflite_fp16_model)

(3)获取输入、输出的张量

def getTensor():
    gf = tf.GraphDef()
    m_file = open(modelPb, 'rb')
    gf.ParseFromString(m_file.read())

    with open(saveFile, 'a') as the_file:
        for n in gf.node:
            the_file.write(n.name + '
')

    file = open(saveFile, 'r')
    data = file.readlines()
    print("output name = "+data[len(data) - 1])


    print("Input name = ")
    file.seek(0)
    print(file.readline())

  

4、工具转换

tflite_convert(tersorflow>=1.9)或者toco (1.9以前)

(1)tflite_convert

参考https://www.tensorflow.org/lite/convert/cmdline_examples

(2)toco

 tflite模型的生成第5张

toco ^

--graph_def_file "E:AI...xxx.pb" ^
--output_file=$OUTPUT_DIR/detect.tflite ^
--input_shapes=1,300,300,3 ^
--input_arrays=image_tensor ^
--output_arrays=detection_classes ^
--inference_type=QUANTIZED_UINT8 ^
--mean_values=128 ^
--std_dev_values=128 ^
--change_concat_input_ranges=false ^
--allow_custom_ops

  

三、tensorflow环境搭建

1、安装Anaconda,请参考其它文章

2、添加Anaconda的国内镜像

因为下载国外的资源太慢了,安装环境前先配置镜像

(1)操作

# 添加Anaconda的TUNA镜像

conda config --add channels https://mirrors.tuna.tsinghua.edu.cn/anaconda/pkgs/free/

# 设置搜索时显示通道地址

conda config --set show_channel_urls yes

#删除镜像源

conda config --remove-key $channels

(2)Anaconda 国内镜像源整理

https://blog.csdn.net/brazy/article/details/88544505

(3)安装时错误的处理

A、出现错误可切换镜像会多试几次

ERROR: No matching distribution found for tensorboard<2.2.0,>=2.1.0 (from tensorflow==2.1.0)

B、可以忽略某个有问题的依赖包

pip install -U --ignore-installed wrapt enum34 simplejson netaddr

ERROR: Cannot uninstall 'wrapt'. It is a distutils installed project and thus we cannot accurately determine which files belong to it which would lead to only a partial uninstall.

3、安装tensorflow环境

(1)创建对应Python的tensorflow环境

conda create -n tensorflow python=3.6.3

conda create -n tensorflow python=3.5.2

(2)激活

activate tensorflow / deactivate

4、下载及安装tensorflow

(1)下载

选择合适的版本下载 https://pypi.org/project/tensorflow/#modal-close

 tflite模型的生成第6张

 tflite模型的生成第7张

(2)安装

pip install F:cp35 ensorflow-1.15.2-cp35-cp35m-win_amd64.whl

,安装高版本的需要预留足够多的空间(如2.0大概需要2G)

(3)验证

python》import tensorflow as tf》print(tf.__version__)

(4)卸载

activate tensorflow

pip uninstall tensorflow

(5)错误

A、windows tensorflow ImportError: DLL load failed: 找不到指定的模块,Failed to load the native TensorFlow runtime.

方案1:

遇到这个问题需要利用vs的dumpbin.exe来查询dll的依赖情况,然后通过where指令确认哪个库不存在,然后对应下载便可,

 D:developtoolsvs2015VCindumpbin.exe /dependents D:developtoolsAnaconda3Libsite-packages ensorflow_corepython\_pywrap_tensorflow_internal.pyd

结果:并没有像文章所说的一样发现了错误

https://blog.csdn.net/u011517332/article/details/90743579

方案2:

pillow是python中的一个图像处理库,是anaconda中自带的。但可能因为pillow的版本较老,所以需要更新一下

conda uninstall pillow

conda update pip

pip install pillow

https://blog.csdn.net/weixin_39750084/article/details/85722233

结果:依然没解决

方案3:

最新的tensorflow安装包对于比较老的处理器不再支持

https://blog.csdn.net/lchzh1994/article/details/81223726

结果:然后再安装tensorflow-2.0.1-cp36-cp36m-win_amd64,over了(注意:tensorflow1与2写法都有很大的区别)

B、tensorflow.lite.python.convert.ConverterError 不是内部或外部命令,也不是可运行的程序或批处理文件

错误信息为:

raise ConverterError("See console for info. %s %s " % (stdout, stderr))

tensorflow.lite.python.convert.ConverterError: See console for info.

b"'toco_from_protos' xb2xbbxcaxc7xc4xdaxb2xbf

处理方式:

安装不同版本的tensorflow及不同的python环境版本(3.6&3.5),中间还采用了pip install tf-nightly,如先安装1.15、tf-nightly、1.14再1.15就突然好了!有时用着用着也出现,重启就好了!(待跟踪)

四、tensorflow-models环境搭建

1、下载models源码

从github上下载超级慢,推荐https://gitee.com/fearless87/tensorflow_models

2、安装protoc

比如我的版本为protoc-3.3.0-win32,https://github.com/protocolbuffers/protobuf/releases

3、配置protoc环境

 tflite模型的生成第8张

 tflite模型的生成第9张

4、编译proto文件

在models/research下运行Windows PowerShell(注意,这里必须是PowerShell,运行cmd会报错),输入如下命令:

Get-ChildItem object_detection/protos/*.proto | Resolve-Path -Relative | %{ protoc $_ --python_out=. }

运行完成后,可以检查object_detection/protos/文件夹,如果每个proto文件都成了对应的以py为后缀的python源码,就说明编译成功了。

5、添加环境变量

根据解释器的位置找到tensorflow

 tflite模型的生成第10张

再加入环境变量文件到对应的位置

 tflite模型的生成第11张

tensorflow_model.pth内容为

 tflite模型的生成第12张

6、运行models/research下的setup.py

python setup.py build

python setup.py install

7、安装完成测试

在models/research下运行如下命令:

python object_detection/builders/model_builder_test.py

出现如下信息,说明已安装成功:

 tflite模型的生成第13张

8、其它

(1)检测现有的tensorflow环境是否存在对应的模块

>>> import tensorflow as tf

>>> dir(tf.contrib.lite)

['DecodeError', 'Interpreter', 'OpHint', 'PY3', 'TocoConverter', '__builtins__', '__cached__', '__doc__', '__file__', '__loader__', '__name__', '__package__', '__spec__', '_freeze_graph', '_freeze_saved_model', '_get_tensors_from_tensor_names', '_global_variables_initializer', '_graph_pb2', '_import_graph_def', '_is_frozen_graph', '_keras', '_session', '_set_tensor_shapes', '_signature_constants', '_tag_constants', '_tensor_name', '_text_format', '_tf_graph_util', 'absolute_import', 'build_toco_convert_protos', 'constants', 'convert_op_hints_to_stubs', 'division', 'print_function', 'toco_convert', 'toco_convert_protos']

五、参考

安装Tensorflow windows10

https://blog.csdn.net/lucboll/article/details/94001177

tensorflow下载

https://pypi.org/project/tensorflow/#modal-close

windows10下安装TensorFlow Object Detection API

https://blog.csdn.net/qq_28019591/article/details/82023949

Tensorflow模型量化实践2--量化自己训练的模型

https://zhuanlan.zhihu.com/p/90690452

TensorFlow模型优化工具:float16量化,模型大小轻轻松松减少一半

https://blog.csdn.net/u011984148/article/details/99523526

tensorflow三种加载模型的方法和三种模型保存文件(.ckpt,.pb, SavedModel)

https://www.cnblogs.com/biandekeren-blog/p/11876032.html

TensorFlow中的模型保存文件

https://blog.csdn.net/weixin_39505272/article/details/91350714

Tensorflow 模型转 tflite ,在安卓端使用

https://blog.csdn.net/sinat_34022298/article/details/81569769?utm_source=distribute.pc_relevant.none-task

Tensorflow 模型转换 .pb convert to .lite实例

https://www.jb51.net/article/180158.htm

tf-nightly

https://download.csdn.net/download/qq_40276310/10878873

开始使用 TensorFlow Lite

https://tensorflow.google.cn/lite/guide/get_started#2_convert_the_model_format

免责声明:文章转载自《tflite模型的生成》仅用于学习参考。如对内容有疑问,请及时联系本站处理。

上篇Spring MVC重定向和转发及异常处理command injection命令注入下篇

宿迁高防,2C2G15M,22元/月;香港BGP,2C5G5M,25元/月 雨云优惠码:MjYwNzM=

随便看看

【原生】CocosCreator Android和游戏的通讯 (Java和TS互相调用、传递JSON数据、监听返回键)

Cocos版本:2.4.4参考:Cocos文档-Java原生反射机制Cocos文档-JSB使用指南-在Cocos中调用Android方法2在Android中调用Cocos方法3传输JSON数据4倾听返回键5 Cocos和Android相互调用时遇到的问题,TypeScript方法可以在Java中调用,Java方法可以在TypeScript中调用。在Cocos...

华为交换机堆叠配置

请参考华为交换机的配置堆栈。[Leaf1-stack-port0/1]portinterfaceg0/0/12启用物理接口12加入堆栈组[Leaf1]stackslot0priority255修改优先级255,默认值为100警告:不要频繁修改优先级,因为它会使堆栈分裂。持续...

ERROR [IM002] [Microsoft][ODBC 驱动程序管理器] 未发现数据源名称并且未指定默认驱动程序

使用C#生成应用程序以及读取和写入dbfs时,打开方法error[IM002][Microsoft][ODBC驱动程序管理器]中发生错误。找不到数据源名称,也未指定默认驱动程序。这个程序以前使用得很好。升级和修改后,在测试中发现了问题。为了追踪来源,我曾经是一个32位操作系统。现在我安装了一个win764位操作系统。从控制面板到管理工具再到ODBC驱动程序,...

PowerQuery清理非文件名字符(清除指定列表中的所有字符)

在左侧导航窗格的空白区域右击,依次找到空白查询项接下来的思路是:遍历列表SearchList中的所有项,依次清理Data表中所有想要处理的列。第三个参数是一个函数:它告诉List.Accumulate函数,在每一次使用SearchList中某一项操作Data表时,其操作的方式是如何的。...

springMVC使用map接收入参 + mybatis使用map 传入查询参数

测试示例:控制器层使用映射来接收请求参数。从Debug中可以看到,请求中的参数值都是字符串形式。如果接收参数的映射直接传输到服务,mybatis将在接收参数时报告错误。因此,您需要首先对请求中的参数1packageorg.slsale进行预处理。测验23导入java.util。日期4导入java.util。HashMap;5导入java.ut...

可爱猫+python——定制化微信机器人

框架是模拟真实用户操作,只要不违法乱纪,是不用担心账号冻结问题的。...