Keras模型的训练后全整数量化

时间:2019-10-30 10:22:23

标签: python tensorflow keras google-coral

我正在尝试对Keras模型进行完整的8位量化训练,以进行编译并部署到EdgeTPU。 我有一个保存为.h5文件的训练有素的Keras模型,正在尝试按照此处指定的步骤操作:https://coral.withgoogle.com/docs/edgetpu/models-intro/,以便部署到Coral Dev Board。

我正在按照以下量化说明进行操作:https://www.tensorflow.org/lite/performance/post_training_quantization#full_integer_quantization_of_weights_and_activations

我正在尝试使用以下代码:

import tensorflow as tf

num_calibration_steps = 100 
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 [X_train_quant_conv]

converter = tf.compat.v1.lite.TFLiteConverter.from_keras_model_file('/tmp/classNN_simple.h5')
converter.optimizations = [tf.lite.Optimize.DEFAULT]
converter.target_spec.supported_ops = [tf.lite.OpsSet.TFLITE_BUILTINS_INT8]
converter.inference_input_type = tf.uint8
converter.inference_output_type = tf.uint8
converter.representative_dataset = representative_dataset_gen
tflite_full_integer_quant_model = converter.convert()

其中X_train_quant_conv是我的训练数据的一部分,转换为np.array,类型为np.float32

运行这段代码时,出现以下错误: ValueError: Cannot set tensor: Dimension mismatch

我尝试以不同方式更改函数representative_dataset_gen(),但是每次遇到新错误时,我都会尝试。我不确定该功能应该如何。我也不确定num_calibration_steps should have的价值是什么。

任何建议或示例都非常感谢。

此问题与已回答的问题非常相似:Convert Keras model to quantized Tensorflow Lite model that can be used on Edge TPU

1 个答案:

答案 0 :(得分:0)

您可能想看一下我的演示脚本on github

这只是一个猜测,因为我看不到X_train_quant_conv的真实含义,但是在我的工作演示中,我一次生成了一张图片(以我为例,它是即时生成的随机数据) 1}}。图像存储为大小为1的批次(例如,对于我的52x52x32图像,张量形状为(1、56、56、32)。彩色图像有32个通道,尽管通常只有3个。我认为representative_dataset_gen()必须产生一个包含张量(或多个?)的列表,其第一维的长度为1。

representative_dataset_gen()