TensorFlow Lite学习笔记
TensorFlow Lite學習筆記
目錄
TensorFlow Lite學習筆記
Tensorflow LIte Demo
模型固化freeze_graph和模型優化optimize_for_inference
將模型轉化為tflite:toco
TensorFlow Lite Converter
模型量化工具:quantize_graph
TensorFlow Lite學習資料集合
??在 TensorFlow Lite 中支持 Core ML
??使用 TensorFlow Lite 進行基于移動設備的對話建模
??Google 第一個 TF 中文教學視頻發布 | TensorFlow Lite 深度解析
??發布新的中文系列視頻 | TensorFlow Lite 概述和模型轉化簡介
??有道云筆記是如何使用 TensorFlow Lite 的?
??中文教學視頻 | 在 Android 中使用 TensorFlow Lite
??中文視頻教學 | 在 iOS 中使用 TensorFlow Lite
??TensorFlow Lite 在 Kika Keyboard 中的應用案例分享
??出門問問:使用 TensorFlow Lite 在嵌入式端部署熱詞檢測模型
Tensorflow LIte Demo
https://github.com/Robinatp/Tensorflow_Lite_Demo
模型固化freeze_graph和模型優化optimize_for_inference
? ? 移動設備有很大的局限性,因此可以進行任何可以減少應用程序占用空間的預處理值得考慮。TensorFlow庫的一種方式是保持較小的移動性,只支持在推理期間常用的操作子集。這是一個合理的方法,因為在移動平臺上很少進行培訓。同樣,它也排除了對大型外部依賴關系的操作的支持。您可以在tensorflow / contrib / makefile / tf_op_files.txt文件中看到支持的操作列表。
? ? 默認情況下,大多數圖表包含TensorFlow的移動版本不支持的培訓操作。TensorFlow不會加載包含不受支持操作的圖(即使不支持的操作與推斷無關)。
? ? 模型固化,可以使用《tensorflow實現將ckpt轉pb文件》的convert_variables_to_constants方法,也可以直接采用腳本freeze_graph的方法。
? ? 模型優化可以使用腳本:tensorflow.python.tools.optimize_for_inference。
? ? 為了避免由不受支持的培訓操作引起的問題,TensorFlow安裝包括一個工具optimize_for_inference,可刪除給定的一組輸入和輸出不需要的所有節點。
? ? 該腳本還進行了一些其他優化,可以幫助加快模型,例如將顯式批量歸一化操作合并到卷積權重中以減少計算次數。這可以根據輸入型號提供30%的速度。運行腳本的方法如下:
python -m tensorflow.python.tools.optimize_for_inference \--input = tf_files / retrained_graph.pb \--output = tf_files / optimized_graph.pb \--input_names =“input”\--output_names = “final_result”運行此腳本將在此創建一個新文件tf_files/optimized_graph.pb。
使用方法如下:
#!/usr/bin/env bash # 模型路徑 model_dir=/home/ubuntu/project/ImageEnhance/triple_path_networks/models/TMFCN_l2_sigmoid_best_sky # ckpt文件 ckpt=tpn-52000 # 輸入輸出tensor input_tensor=orig_images output_tensor=output/Sigmoid # 輸出固話模型 output_pb=frozen_graph2.pb # 輸出優化后的模型 optimize_pb=optimize_graph2.pb# 激活tensorflow source activate tensorflow-cpu-py35# 固話模型 echo 'freeze_graph' freeze_graph \--input_graph=$model_dir/graph.pbtxt \--input_checkpoint=$model_dir/$ckpt \--input_binary=false \--output_graph=$model_dir/$output_pb \--output_node_names=$output_tensorecho 'freeze graph done...'# 模型優化 echo 'optimize_for_inference' python -m tensorflow.python.tools.optimize_for_inference \--input=$model_dir/$output_pb \--output=$model_dir/$optimize_pb \--frozen_graph=True \--input_names=$input_tensor \--output_names=$output_tensorecho 'optimized done...'將模型轉化為tflite:toco
? ? TensorFlow Lite 所用的模型是使用 TOCO 工具從 TensorFlow 模型轉化而來的,來源就是經過冷凍生成的 Frozen Graph。假如你已經得到了一個“夠用”的模型了,而且你也沒有源代碼或者數據來重新進行訓練,那么就使用當前的模型吧,沒有任何問題。但如果你有源代碼和數據,直接使用 TOCO 工具進行模型轉化將會是最好的選擇。示例代碼如下:
《如何將自己開發的模型轉換為TensorFlow Lite可用模型》https://blog.csdn.net/mogoweb/article/details/80152774
《Inception v3 模型重新訓練及模型轉化為tflite》https://www.jianshu.com/p/461912ba51d7
#!/usr/bin/env bash # 模型路徑 model_dir=/home/ubuntu/project/ImageEnhance/triple_path_networks/models/YNet_sigmoid_best_sky# 輸入輸出tensor input_tensor=orig_images output_tensor=output/concat # 輸入優化后的模型 optimize_pb=optimize_graph2.pb# 激活tensorflow source activate tensorflow-cpu-py35# float數據格式轉換 echo 'TF Lite:float' toco \--graph_def_file=$model_dir/$optimize_pb \--output_file=$model_dir/optimize_graph_float_128.tflite \--output_format=TFLITE \--inference_type=FLOAT \--input_type=FLOAT \--input_arrays=$input_tensor \--output_arrays=$output_tensor \--input_shapes=1,128,128,3# QUANTIZED_UINT8格式 echo 'TF Lite:QUANTIZED_UINT8' toco \--graph_def_file=$model_dir/$optimize_pb \--output_file=$model_dir/optimize_graph_uint8_128.tflite \--output_format=TFLITE \--input_arrays=$input_tensor \--output_arrays=$output_tensor \--input_shapes=1,128,128,3 \--inference_type=QUANTIZED_UINT8 \--inference_input_type=QUANTIZED_UINT8 \--mean_value=128 \--std_dev_values=128 \--default_ranges_min=0 \--default_ranges_max=255TensorFlow Lite Converter
? ? 當然,也可以直接使用Python的TFLiteConvert工具,如:
? ? PS:TensorFlow版本需要1.12.0
? ? 官網子類:https://tensorflow.google.cn/lite/convert/python_api?hl=zh-cn
def convert_tflite():graph_def_file = "../models/YNet_sigmoid_best_sky/optimize_graph.pb"# input_arrays = ['image', 'sp', 'Hsp_boxes', 'O_boxes']# output_arrays = ["classification/op_store"]input_arrays = ['orig_images']output_arrays = ['output/concat']out_tflite=os.path.dirname(graph_def_file)out_tflite=os.path.join(out_tflite,'converted_model_64.tflite')input_shapes={"orig_images":[1,64,64,3]}# Converting a GraphDef from session.# converter = lite.TFLiteConverter.from_session(sess, in_tensors, out_tensors)# tflite_model = converter.convert()# open("converted_model.tflite", "wb").write(tflite_model)# Converting a GraphDef from file.converter = lite.TFLiteConverter.from_frozen_graph(graph_def_file, input_arrays, output_arrays,input_shapes)tflite_model = converter.convert()open(out_tflite, "wb").write(tflite_model)# Converting a SavedModel.# converter = lite.TFLiteConverter.from_saved_model(saved_model_dir)# tflite_model = converter.convert()# Converting a tf.keras model.# converter = lite.TFLiteConverter.from_keras_model_file(keras_model)# tflite_model = converter.convert()? ? tflite模型用于移植到移動端,也可以調用tflite的Python接口lite.Interpreter進行推理:
def tflite_test(filename,orig_dir,out_dir,tflite_path,resize_width=0, resize_height=0):images_list =load_data.read_data(filename)images_list=[os.path.join(orig_dir,name) for name in images_list]if not os.path.exists(out_dir):os.makedirs(out_dir)# Get input and output tensors.interpreter = lite.Interpreter(model_path=tflite_path)interpreter.allocate_tensors()input_details = interpreter.get_input_details()output_details = interpreter.get_output_details()input_shape = input_details[0]['shape']print("input_shape:{}".format(input_shape))print(" input_details.index".format(input_details[0]['index']))print("output_details.index".format(output_details[0]['index']))for image_path in images_list:if not os.path.exists(image_path):print("no image:{}".format(image_path))continueorig_image = image_processing.read_image(image_path, 0, 0, normalization=True)orig_shape = orig_image.shapeinput_image = orig_imageif resize_height > 0 and resize_width > 0:input_image = cv2.resize(input_image, (resize_width, resize_height))# 輸入數據的類型必須與tflite模型一致,一般是float32或uint8T0 = datetime.datetime.now()input_data = np.array(input_image[np.newaxis, :],dtype=np.float32)# input_data = np.array(np.random.random_sample(input_shape), dtype=np.float32)interpreter.set_tensor(input_details[0]['index'], input_data)interpreter.invoke()output_data = interpreter.get_tensor(output_details[0]['index'])T1 = datetime.datetime.now()A_net, B_net = np.array_split(output_data, indices_or_sections=2, axis=3)pre_net1 = A_net[0, :, :, :] # tf.squeezepre_net2 = B_net[0, :, :, :]if resize_height > 0 and resize_width > 0:pre_net1 = cv2.resize(pre_net1, (orig_shape[1], orig_shape[0]), interpolation=cv2.INTER_LINEAR)pre_net2 = cv2.resize(pre_net2, (orig_shape[1], orig_shape[0]), interpolation=cv2.INTER_LINEAR)pre_images = np.multiply(pre_net1, orig_image) + pre_net2# 圖像數據溢出保護# pre_images = tf.cast(255.0 * tf.clip_by_value(pre_images, 0, 1), tf.uint8)pre_images = np.clip(pre_images, 0, 1)T2 = datetime.datetime.now()# load_data.show_image("image", pre_images)name = os.path.splitext(os.path.basename(image_path))[0]image_processing.combime_save_image(orig_image, pre_images, out_dir, name,prefix="YNet_pb_resize" + str(resize_height))T3 = datetime.datetime.now()print("processing image:{},shape:{},rum time:tpn:{}ms,mul:{}ms,all:{}ms".format(image_path,pre_images.shape,(T1 - T0).seconds * 1000 + (T1 - T0).microseconds / 1000.0,(T2 - T1).seconds * 1000 + (T2 - T1).microseconds / 1000.0,(T3 - T0).seconds * 1000 + (T3 - T0).microseconds / 1000.0))模型量化工具:quantize_graph
????量化簡單來說就是將32浮點數近似地用8位整數存儲和計算,量化后,模型占用存儲空間減小75%,起到了壓縮模型的效果。
8bit量化簡單的例子:模型屬于同一層的參數值會分布在一個較小的區間內,比如在[-1,1]之間,可以把同一層的所有參數都線性映射區間[0, 255],如:
float | Quantized
-------+----------?
-1.0 | 0
1.0 ?| 255
0.0 ?| 125
執行命令:
bazel-bin/tensorflow/tools/quantization/quantize_graph \ --input=./tmp/classify_image_graph_def.pb \ --output_node_names="softmax" --output=./tmp/quantized_graph.pb \ --mode=eightbit參考資料:https://blog.csdn.net/gaofeipaopaotang/article/details/81186891?
TensorFlow Lite學習資料集合
官網教程:https://www.tensorflow.org/lite/
??在 TensorFlow Lite 中支持 Core ML
iOS 開發者可以利用 Core ML 的優勢來部署 TensorFlow 模型。
?
??使用 TensorFlow Lite 進行基于移動設備的對話建模
這個應用提供了 TensorFlow Lite 實現的一個自然語言應用示例,這些舉措旨在讓開發者和研究人員更輕松地構建由機器上推理驅動的新機器智能功能。
?
??Google 第一個 TF 中文教學視頻發布 | TensorFlow Lite 深度解析
TensorFlow Lite 的深度解析視頻,主要講述 TensorFlow Lite 模型文件格式,并可視化以幫助大家記憶理解,也包含 TensorFlow Lite 的具體加載運行過程,并給出關鍵的數據結構描述,同樣以可視化的形式呈現給大家。
?
??發布新的中文系列視頻 | TensorFlow Lite 概述和模型轉化簡介
Google 的工程師 Yizhen Fu 為你帶來 TensorFlow Lite 的概述和模型轉化簡介,以及使用過程中會接觸到的一些概念、術語和資源類型等。
?
??有道云筆記是如何使用 TensorFlow Lite 的?
本文將介紹我們是如何將 TFLite 運用在有道云筆記中的文檔識別工作中的,以及 Tflite 都有些什么特性。
?
??中文教學視頻 | 在 Android 中使用 TensorFlow Lite
本期視頻將與大家分享 Android 平臺上的一些 TensorFlow Lite 應用。
?
??中文視頻教學 | 在 iOS 中使用 TensorFlow Lite
本期視頻為大家帶來如何在 iOS 中使用 TensorFlow Lite 的教學視頻
?
??TensorFlow Lite 在 Kika Keyboard 中的應用案例分享
Kika keyboard 與 TensorFlow Lite
?
??出門問問:使用 TensorFlow Lite 在嵌入式端部署熱詞檢測模型
我們使用 TensorFlow Lite 作為神經網絡模型的部署框架,既能夠很好地兼容基于 TensorFlow 的模型訓練流程,也能夠提供非常高效和輕量的嵌入式端運行時 (Runtime)。
總結
以上是生活随笔為你收集整理的TensorFlow Lite学习笔记的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: OpenCV+yolov2-tiny实现
- 下一篇: NLP学习笔记