TensorFlow Lite学习笔记

矫情吗;* 2022-05-12 14:56 346阅读 0赞

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

  1. 移动设备有很大的局限性,因此可以进行任何可以减少应用程序占用空间的预处理值得考虑。TensorFlow库的一种方式是保持较小的移动性,只支持在推理期间常用的操作子集。这是一个合理的方法,因为在移动平台上很少进行培训。同样,它也排除了对大型外部依赖关系的操作的支持。您可以在[tensorflow / contrib / makefile / tf\_op\_files.txt][tensorflow _ contrib _ makefile _ tf_op_files.txt]文件中看到支持的操作列表。
  2. 默认情况下,大多数图表包含TensorFlow的移动版本不支持的培训操作。TensorFlow不会加载包含不受支持操作的图(即使不支持的操作与推断无关)。
  1. 模型固化,可以使用《[tensorflow实现将ckptpb文件][tensorflow_ckpt_pb]》的***convert\_variables\_to\_constants***方法,也可以直接采用脚本***freeze\_graph***的方法。
  2. 模型优化可以使用脚本:tensorflow.python.tools.optimize\_for\_inference
  1. 为了避免由不受支持的培训操作引起的问题,TensorFlow安装包括一个工具optimize\_for\_inference,可删除给定的一组输入和输出不需要的所有节点。
  2. 该脚本还进行了一些其他优化,可以帮助加快模型,例如将显式批量归一化操作合并到卷积权重中以减少计算次数。这可以根据输入型号提供30%的速度。运行脚本的方法如下:
  3. python -m tensorflow.python.tools.optimize_for_inference \
  4. --input = tf_files / retrained_graph.pb \
  5. --output = tf_files / optimized_graph.pb \
  6. --input_names =“input\
  7. --output_names = final_result

运行此脚本将在此创建一个新文件tf_files/optimized_graph.pb。

使用方法如下:

  1. #!/usr/bin/env bash
  2. # 模型路径
  3. model_dir=/home/ubuntu/project/ImageEnhance/triple_path_networks/models/TMFCN_l2_sigmoid_best_sky
  4. # ckpt文件
  5. ckpt=tpn-52000
  6. # 输入输出tensor
  7. input_tensor=orig_images
  8. output_tensor=output/Sigmoid
  9. # 输出固话模型
  10. output_pb=frozen_graph2.pb
  11. # 输出优化后的模型
  12. optimize_pb=optimize_graph2.pb
  13. # 激活tensorflow
  14. source activate tensorflow-cpu-py35
  15. # 固话模型
  16. echo 'freeze_graph'
  17. freeze_graph \
  18. --input_graph=$model_dir/graph.pbtxt \
  19. --input_checkpoint=$model_dir/$ckpt \
  20. --input_binary=false \
  21. --output_graph=$model_dir/$output_pb \
  22. --output_node_names=$output_tensor
  23. echo 'freeze graph done...'
  24. # 模型优化
  25. echo 'optimize_for_inference'
  26. python -m tensorflow.python.tools.optimize_for_inference \
  27. --input=$model_dir/$output_pb \
  28. --output=$model_dir/$optimize_pb \
  29. --frozen_graph=True \
  30. --input_names=$input_tensor \
  31. --output_names=$output_tensor
  32. echo 'optimized done...'

将模型转化为tflite:toco

  1. 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

  1. #!/usr/bin/env bash
  2. # 模型路径
  3. model_dir=/home/ubuntu/project/ImageEnhance/triple_path_networks/models/YNet_sigmoid_best_sky
  4. # 输入输出tensor
  5. input_tensor=orig_images
  6. output_tensor=output/concat
  7. # 输入优化后的模型
  8. optimize_pb=optimize_graph2.pb
  9. # 激活tensorflow
  10. source activate tensorflow-cpu-py35
  11. # float数据格式转换
  12. echo 'TF Lite:float'
  13. toco \
  14. --graph_def_file=$model_dir/$optimize_pb \
  15. --output_file=$model_dir/optimize_graph_float_128.tflite \
  16. --output_format=TFLITE \
  17. --inference_type=FLOAT \
  18. --input_type=FLOAT \
  19. --input_arrays=$input_tensor \
  20. --output_arrays=$output_tensor \
  21. --input_shapes=1,128,128,3
  22. # QUANTIZED_UINT8格式
  23. echo 'TF Lite:QUANTIZED_UINT8'
  24. toco \
  25. --graph_def_file=$model_dir/$optimize_pb \
  26. --output_file=$model_dir/optimize_graph_uint8_128.tflite \
  27. --output_format=TFLITE \
  28. --input_arrays=$input_tensor \
  29. --output_arrays=$output_tensor \
  30. --input_shapes=1,128,128,3 \
  31. --inference_type=QUANTIZED_UINT8 \
  32. --inference_input_type=QUANTIZED_UINT8 \
  33. --mean_value=128 \
  34. --std_dev_values=128 \
  35. --default_ranges_min=0 \
  36. --default_ranges_max=255

TensorFlow Lite Converter

  1. 当然,也可以直接使用PythonTFLiteConvert工具,如:
  1. PSTensorFlow版本需要1.12.0
  2. 官网子类:[https://tensorflow.google.cn/lite/convert/python\_api?hl=zh-cn][https_tensorflow.google.cn_lite_convert_python_api_hl_zh-cn]
  1. def convert_tflite():
  2. graph_def_file = "../models/YNet_sigmoid_best_sky/optimize_graph.pb"
  3. # input_arrays = ['image', 'sp', 'Hsp_boxes', 'O_boxes']
  4. # output_arrays = ["classification/op_store"]
  5. input_arrays = ['orig_images']
  6. output_arrays = ['output/concat']
  7. out_tflite=os.path.dirname(graph_def_file)
  8. out_tflite=os.path.join(out_tflite,'converted_model_64.tflite')
  9. input_shapes={"orig_images":[1,64,64,3]}
  10. # Converting a GraphDef from session.
  11. # converter = lite.TFLiteConverter.from_session(sess, in_tensors, out_tensors)
  12. # tflite_model = converter.convert()
  13. # open("converted_model.tflite", "wb").write(tflite_model)
  14. # Converting a GraphDef from file.
  15. converter = lite.TFLiteConverter.from_frozen_graph(
  16. graph_def_file, input_arrays, output_arrays,input_shapes)
  17. tflite_model = converter.convert()
  18. open(out_tflite, "wb").write(tflite_model)
  19. # Converting a SavedModel.
  20. # converter = lite.TFLiteConverter.from_saved_model(saved_model_dir)
  21. # tflite_model = converter.convert()
  22. # Converting a tf.keras model.
  23. # converter = lite.TFLiteConverter.from_keras_model_file(keras_model)
  24. # tflite_model = converter.convert()
  25. tflite模型用于移植到移动端,也可以调用tflitePython接口lite.Interpreter进行推理:
  26. def tflite_test(filename,orig_dir,out_dir,tflite_path,resize_width=0, resize_height=0):
  27. images_list =load_data.read_data(filename)
  28. images_list=[os.path.join(orig_dir,name) for name in images_list]
  29. if not os.path.exists(out_dir):
  30. os.makedirs(out_dir)
  31. # Get input and output tensors.
  32. interpreter = lite.Interpreter(model_path=tflite_path)
  33. interpreter.allocate_tensors()
  34. input_details = interpreter.get_input_details()
  35. output_details = interpreter.get_output_details()
  36. input_shape = input_details[0]['shape']
  37. print("input_shape:{}".format(input_shape))
  38. print(" input_details.index".format(input_details[0]['index']))
  39. print("output_details.index".format(output_details[0]['index']))
  40. for image_path in images_list:
  41. if not os.path.exists(image_path):
  42. print("no image:{}".format(image_path))
  43. continue
  44. orig_image = image_processing.read_image(image_path, 0, 0, normalization=True)
  45. orig_shape = orig_image.shape
  46. input_image = orig_image
  47. if resize_height > 0 and resize_width > 0:
  48. input_image = cv2.resize(input_image, (resize_width, resize_height))
  49. # 输入数据的类型必须与tflite模型一致,一般是float32或uint8
  50. T0 = datetime.datetime.now()
  51. input_data = np.array(input_image[np.newaxis, :],dtype=np.float32)
  52. # input_data = np.array(np.random.random_sample(input_shape), dtype=np.float32)
  53. interpreter.set_tensor(input_details[0]['index'], input_data)
  54. interpreter.invoke()
  55. output_data = interpreter.get_tensor(output_details[0]['index'])
  56. T1 = datetime.datetime.now()
  57. A_net, B_net = np.array_split(output_data, indices_or_sections=2, axis=3)
  58. pre_net1 = A_net[0, :, :, :] # tf.squeeze
  59. pre_net2 = B_net[0, :, :, :]
  60. if resize_height > 0 and resize_width > 0:
  61. pre_net1 = cv2.resize(pre_net1, (orig_shape[1], orig_shape[0]), interpolation=cv2.INTER_LINEAR)
  62. pre_net2 = cv2.resize(pre_net2, (orig_shape[1], orig_shape[0]), interpolation=cv2.INTER_LINEAR)
  63. pre_images = np.multiply(pre_net1, orig_image) + pre_net2
  64. # 图像数据溢出保护
  65. # pre_images = tf.cast(255.0 * tf.clip_by_value(pre_images, 0, 1), tf.uint8)
  66. pre_images = np.clip(pre_images, 0, 1)
  67. T2 = datetime.datetime.now()
  68. # load_data.show_image("image", pre_images)
  69. name = os.path.splitext(os.path.basename(image_path))[0]
  70. image_processing.combime_save_image(orig_image, pre_images, out_dir, name,
  71. prefix="YNet_pb_resize" + str(resize_height))
  72. T3 = datetime.datetime.now()
  73. print("processing image:{},shape:{},rum time:tpn:{}ms,mul:{}ms,all:{}ms"
  74. .format(image_path,
  75. pre_images.shape,
  76. (T1 - T0).seconds * 1000 + (T1 - T0).microseconds / 1000.0,
  77. (T2 - T1).seconds * 1000 + (T2 - T1).microseconds / 1000.0,
  78. (T3 - T0).seconds * 1000 + (T3 - T0).microseconds / 1000.0))

模型量化工具:quantize_graph

  1. 量化简单来说就是将32浮点数近似地用8位整数存储和计算,量化后,模型占用存储空间减小75%,起到了压缩模型的效果。

8bit量化简单的例子:模型属于同一层的参数值会分布在一个较小的区间内,比如在[-1,1]之间,可以把同一层的所有参数都线性映射区间[0, 255],如:

float | Quantized

-———+—————

-1.0 | 0

1.0 | 255

0.0 | 125

执行命令:

  1. bazel-bin/tensorflow/tools/quantization/quantize_graph \
  2. --input=./tmp/classify_image_graph_def.pb \
  3. --output_node_names="softmax" --output=./tmp/quantized_graph.pb \
  4. --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)。

发表评论

表情:
评论列表 (有 0 条评论,346人围观)

还没有评论,来说两句吧...

相关阅读

    相关 TensorFlow Lite入门

    TensorFlow Lite介绍 TensorFlow Lite的目标是移动和嵌入式设备,它赋予了这些设备在终端本地运行机器学习模型的能力,从而不再需要向云端服务器发送