【发布时间】:2020-12-27 14:39:40
【问题描述】:
我使用 Tensorflow 1.15.3 量化 Keras h5 模型(TF 1.13 ; keras_vggface 模型),以将其与 NPU 一起使用。我用来转换的代码是:
converter = tf.lite.TFLiteConverter.from_keras_model_file(saved_model_dir + modelname)
converter.optimizations = [tf.lite.Optimize.DEFAULT]
converter.representative_dataset = representative_dataset_gen
converter.target_spec.supported_ops = [tf.lite.OpsSet.TFLITE_BUILTINS_INT8]
converter.inference_input_type = tf.int8 # or tf.uint8
converter.inference_output_type = tf.int8 # or tf.uint8
tflite_quant_model = converter.convert()
我得到的量化模型乍一看还不错。 层的输入类型为int8,filter为int8,bias为int32,输出为int8。
但是,模型在输入层之后有一个量化层,输入层是 float32 [见下图]。但似乎 NPU 也需要输入为 int8。
有没有一种方法可以在不使用转换层但也使用 int8 作为输入的情况下进行完全量化?
正如你在上面看到的,我使用了:
converter.inference_input_type = tf.int8
converter.inference_output_type = tf.int8
编辑
来自用户 dtlam 的解决方案
尽管模型仍然无法使用 google NNAPI 运行,但使用 TF 1.15.3 或 TF2.2.0 使用 int8 量化模型并在 int8 中输出的解决方案是,感谢 delan:
...
converter = tf.lite.TFLiteConverter.from_keras_model_file(saved_model_dir + modelname)
def representative_dataset_gen():
for _ in range(10):
pfad='pathtoimage/000001.jpg'
img=cv2.imread(pfad)
img = np.expand_dims(img,0).astype(np.float32)
# Get sample input data as a numpy array in a method of your choosing.
yield [img]
converter.representative_dataset = representative_dataset_gen
converter.optimizations = [tf.lite.Optimize.DEFAULT]
converter.representative_dataset = representative_dataset_gen
converter.target_spec.supported_ops = [tf.lite.OpsSet.TFLITE_BUILTINS_INT8]
converter.experimental_new_converter = True
converter.target_spec.supported_types = [tf.int8]
converter.inference_input_type = tf.int8
converter.inference_output_type = tf.int8
quantized_tflite_model = converter.convert()
if tf.__version__.startswith('1.'):
open("test153.tflite", "wb").write(quantized_tflite_model)
if tf.__version__.startswith('2.'):
with open("test220.tflite", 'wb') as f:
f.write(quantized_tflite_model)
【问题讨论】:
标签: tensorflow tensorflow-lite quantization