python - 将 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
但它已被弃用)
解决方案
我相信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 模型的训练后全整数量化
推荐阅读
- typescript - 如何在新的组合 API 中键入计算属性?
- amazon-cognito - 将 Github 身份提供商添加到 AWS Cognito
- php - 使用 php 在另一个页面上使用 header() 函数提交 jquery 后重定向页面
- security - 使用动态用户进行 RabbitMQ 用户身份验证
- xamarin - Xamarin 表单 GoogleAds 显示外壳底部
- python-3.x - 在 Python 3 中将 16 位十六进制字符串转换为双精度值
- c# - Moq - 模拟 DbSet
.AddAsync 不引发任何调用 - python - mypy 找不到黑色的类型提示
- html - 如何在标签旁边的输入集中在具有多个标签的表单中并在css中输入时更改标签中文本的颜色
- c++ - GRPC C++ 异步服务器如何区分 WritesDone 和断开的连接