由於IOS App需要使用已訓練的tensorflow模型進行物體檢測,特將此過程記錄下來已備不時之需。
一、tflite是什么
TensorFlow Lite 的設計旨在在各種設備上高效執行模型。這種高效部分源於在存儲模型時,采用了一種特殊的格式。TensorFlow 模型在能被 TensorFlow Lite 使用前,必須轉換成這種格式。

由上圖可知:
tflite是從訓練的模型轉換而來的;
tflite是為了在App設備上使用;
二、從訓練結果到tflite
1、ckpt訓練模型說明

訓練過程中產生的文件說明:
Checkpoint——

保留最近幾次的訓練結果的索引
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類似

3、tflite pb轉tflite
(1)直接轉換
def convertToLite_normal():
graph_def_file=r'E:\AI\...\tflite_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\...\bbc_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\...\tflite_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\...\bbc_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 + '\n')
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

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


(2)安裝
pip install F:\cp35\tensorflow-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:\developtools\vs2015\VC\bin\dumpbin.exe /dependents D:\developtools\Anaconda3\Lib\site-packages\tensorflow_core\python\_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.\n%s\n%s\n" % (stdout, stderr))
tensorflow.lite.python.convert.ConverterError: See console for info.
b"'toco_from_protos' \xb2\xbb\xca\xc7\xc4\xda\xb2\xbf\
處理方式:
安裝不同版本的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環境


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

再加入環境變量文件到對應的位置

tensorflow_model.pth內容為

6、運行models/research下的setup.py
python setup.py build
python setup.py install
7、安裝完成測試
在models/research下運行如下命令:
python object_detection/builders/model_builder_test.py
出現如下信息,說明已安裝成功:

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 ,在安卓端使用
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
