0

我已经使用 yolov4 darkenet Alexyab 完成了对象检测模型的训练,然后使用此存储库 https://github.com/hunglc007/tensorflow-yolov4-tflite将生成的权重文件转换为 tensorflow lite 并且我能够转换 yolo权重为 pb 和 tflite float16,但使用此 repo 转换为 tflite int8 时存在问题。我尝试了很多方法将其转换为 tflite int8。

我现在正在使用需要 tflite int8 量化的珊瑚开发板,请指导我如何将 pb 权重文件转换为 tflite int8。

版本:tensorflow 1.15 python 3.6.9 CUDA 版本 V9.1.85

4

2 回答 2

0

我建议您首先.h5使用存储库将 yolov4 权重转换为 keras 权重。

获得.h5权重后,您可以使用此代码将 keras 模型转换为 tflite。

import tensorflow.compat.v1 as tf
import numpy
import cv2

def representative_dataset_gen():
  num_calibration_steps = 100 # should be a subset of your dataset size
  imgs = []
  batch_size = 1
  for _ in range(num_calibration_steps):
    img = cv2.imread(img_file)
    img = img / 255.0
    img = img.astype(np.float32)
    imgs.append(img)
  
  imgs = np.array(imgs)
  images = tf.data.Dataset.from_tensor_slices(imgs).batch(1)
  for i in images.take(batch_size):
    yield [i]

converter = tf.lite.TFLiteConverter.from_keras_model_file("path_to_h5_weights")
converter.optimizations = [tf.lite.Optimize.DEFAULT]
converter.target_spec.supported_ops = [tf.lite.OpsSet.TFLITE_BUILTINS_INT8]
converter.inference_input_type = tf.int8  # or tf.uint8
converter.inference_output_type = tf.int8  # or tf.uint8
converter.representative_dataset = representative_dataset_gen
tflite_model = converter.convert()

# Save the model.
with open('model.tflite', 'wb') as f:
  f.write(tflite_model)

来源 - Tensorflow 量化

tflite 转换

生成有代表性的数据集

于 2021-04-08T05:09:52.263 回答
0

首先,我推荐使用最新的 TF 版本,例如 2.4.1 或 nightly 版本进行转换,这是对 TFLite 转换的很多改进。

以上yolov4 github也需要tf 2.3.0以上版本。

如果你在升级 TF 版本后仍有创建 int8 量化模型的经验。请分享您收到的错误消息的更多详细信息。

于 2021-04-07T11:13:31.503 回答