【问题标题】:Convert Keras model to quantized Tensorflow Lite model that can be used on Edge TPU将 Keras 模型转换为可在 Edge TPU 上使用的量化 Tensorflow Lite 模型
【发布时间】:2019-09-26 19:31:31
【问题描述】:

我有一个想要在 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

这是因为我需要量化模型,但我不知道该怎么做。我找到了this page,它告诉我如何执行此操作,但它希望我制作一个输入数据生成器。这是它提供的示例:

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 的引用,但它已被弃用)

【问题讨论】:

    标签: python tensorflow keras tensorflow-lite tpu


    【解决方案1】:

    我相信num_calibration_steps 只是转换器使用您的代表集来确定量化级别的次数。只是一个猜测,但它可能会多次从您的代表集中子样本(引导或折刀)。我自己仍在调查整个过程,但如果我只为每个产量传递一个图像,并在大约 100 个时使用num_calibration_steps(例如,100 个代表性图像),它似乎对我有用。你可以看我的演示脚本on 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]
    

    另请参阅我对这个问题的类似回复: Post-training full integer quantization of Keras model

    【讨论】:

    • 我做了更多的测试。似乎代表数据集_gen() 必须以我描述的格式产生一个且只有一个图像。所以没有自举或折刀。 num_calibration_steps 变量可能更恰当地命名为 num_calibration_images。虽然没有什么可以阻止某人多次使用同一张图片,所以我猜 num_calibration_steps 仍然有效并且是更笼统的描述。
    • 谢谢。您的简单示例帮助我解决了我的错误。我最初以列表中的 3D 数组 (HxWxC)(即[3d_image_array])或 4D 数组 (NxHxWxC) 的形式生成单个图像。但似乎 TfLite 希望生成器在列表中生成一个 4D 数组(即[4d_image_array])Brrr,讨厌的错误
    猜你喜欢
    • 2019-05-14
    • 1970-01-01
    • 2019-06-28
    • 1970-01-01
    • 2018-09-07
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-04-14
    相关资源
    最近更新 更多