首页 > 解决方案 > 将 Keras 模型转换为可在 Edge TPU 上使用的量化 Tensorflow Lite 模型

问题描述

我有一个想要在 Coral Edge TPU 设备上运行的 Keras 模型。为此,它需要是具有全整数量化的 Tensorflow Lite 模型。我能够将模型转换为 TFLite 模型:

model.save('keras_model.h5')

converter = tf.lite.TFLiteConverter.from_keras_model_file("keras_model.h5")
tflite_model = converter.convert()
open("converted_model.tflite", "wb").write(tflite_model)

但是当我运行时edgetpu_compiler converted_model.tflite,我得到了这个错误:

Edge TPU Compiler version 2.0.267685300
Invalid model: converted_model.tflite
Model not quantized

这是因为我需要量化模型,但我不知道该怎么做。我发现这个页面告诉我如何做到这一点,但它希望我制作一个输入数据生成器。这是它提供的示例:

def representative_dataset_gen():
  for _ in range(num_calibration_steps):
    # Get sample input data as a numpy array in a method of your choosing.
    yield [input]

如何调整此代码以处理我的输入数据?从哪里来num_calibration_steps?有一个更好的方法吗?(我看到了参考,tf.contrib.tpu.keras_to_tpu_model但它已被弃用)

标签: pythontensorflowkerastensorflow-litetpu

解决方案


我相信num_calibration_steps只是转换器使用您的代表集来确定量化级别的次数。只是一个猜测,但它可能会多次从您的代表集中进行子采样(引导或折刀)。我自己仍在研究整个过程,但如果我只为每个产量传递一个图像,并使用num_calibration_steps大约 100 个(例如,100 个代表性图像),它似乎对我有用。你可以在 github 上看到我的演示脚本。

关键部分是:

image_shape = (56, 56, 32)

def representative_dataset_gen():
    num_calibration_images = 10
    for i in range(num_calibration_images):
        image = tf.random.normal([1] + list(image_shape))
        yield [image]

另请参阅我对这个问题的类似回复: Keras 模型的训练后全整数量化


推荐阅读