我正在使用Keras/Tensorflow开发一个将部署到低端MCU的人工神经网络(ANN)。为此,我使用了Tensorflow Lite提供的后训练量化机制对原始ANN进行了量化。如果权重确实被量化为int8,那么偏置从float转换为了int32。考虑到我打算在CMSIS-NN中实现这个ANN,这是一个问题,因为它们只支持int8和int16数据类型。
是否可以配置TF Lite以将偏置也量化为int8?以下是我正在执行的代码:
def quantizeToInt8(representativeDataset): # 将数据集转换为float32 data = tf.cast(representativeDataset, tf.float32) data = tf.data.Dataset.from_tensor_slices((data)).batch(1) # 返回每个迭代一个数据点的生成器函数 def representativeDatasetGen(): for inputValue in data: yield[inputValue] # ANN量化 model = tf.keras.models.load_model("C:/Users/miguel/Documents/Universidade/PhD/Code_Samples/TensorFlow/originalModel.h5") converter = tf.lite.TFLiteConverter.from_keras_model(model) converter.optimizations = [tf.lite.Optimize.DEFAULT] converter.representative_dataset = representativeDatasetGen converter.target_spec.supported_ops = [tf.lite.OpsSet.TFLITE_BUILTINS_INT8] converter.target_spec.supported_types = [tf.int8] converter.inference_type = tf.int8 converter.inference_input_type = tf.int8 # 或tf.uint8 converter.inference_output_type = tf.int8 # 或tf.uint8 tflite_quant_model = converter.convert() return tflite_quant_model
回答:
来自评论
无法配置
TFLite
来实现这一点。偏置
被有意设为int32
,否则量化的准确性不会很好。为了使其工作,你需要添加一个新的操作或自定义操作,然后创建一个全新的自定义量化工具。(摘自Meghna Natraj的评论)