# 使用 Python API 进行转换和量化

Source: [https://docs.qualcomm.com/doc/80-70014-54Y/topic/convert-and-quantize-using-python-apis.html](https://docs.qualcomm.com/doc/80-70014-54Y/topic/convert-and-quantize-using-python-apis.html)

TensorFlow 提供 API 来将 TensorFlow Saved Model 或 Keras 模型转换为 TensorFlow Lite 模型。

- tf.lite.TFLiteConverter.from\_saved\_model()（推荐）：转换 SavedModel
- tf.lite.TFLiteConverter.from\_keras\_model()：转换 Keras 模型

## 转换 TensorFlow SavedModel（推荐）

以下示例显示如何将以 saved\_model 格式保存的 TensorFlow 模型转换为 TensorFlow Lite 模型：

    import tensorflow as tf
    
    # Convert the model
    Saved_model_dir = “/path/to/tf/model/in/saved_model/format”
    converter = tf.lite.TFLiteConverter.from_saved_model(saved_model_dir)
    tflite_model = converter.convert()
    
    # Save the model
    with open(‘model.tflite’, ‘wb’) as f:
        f.write(tflite_model)
    Copy to clipboard

Note: 转换后的 TensorFlow Lite 模型未经过量化，其数据为 32 位浮点精度。

## 转换 Keras 模型

以下示例展示如何将 Keras 模型转换为 TensorFlow Lite 模型：

    import tensorflow as tf
    
    # Create a model using high-level tf.keras.* APIs
    model = tf.keras.models.Sequential([
        tf.keras.layers.Dense(units=1, input_shape=[1]),
        tf.keras.layers.Dense(units=16, activation='relu'),
        tf.keras.layers.Dense(units=1)
    ])
    
    # compile the model
    model.compile(optimizer='sgd', loss='mean_squared_error')
    
    # train the model
    model.fit(x=[-1, 0, 1], y=[-3, -1, 1], epochs=5)
    
    # Convert the model to TFLite
    converter = tf.lite.TFLiteConverter.from_keras_model(model)
    tflite_model = converter.convert()
    
    # Save the model
    with open('model.tflite', 'wb') as f:
        f.write(tflite_model)
    Copy to clipboard

Note: 转换后的 TensorFlow Lite 模型未经过量化，其数据为 32 位浮点精度。

## 量化模型

神经网络模型中的量化涉及以下步骤：

1. 量化权重和偏差：这是一个静态步骤，因为权重/偏差已经是训练模型的一部分，可以在不需要额外信息的情况下进行量化。
2. 量化激活层：激活层输出的范围取决于前向传播期间的输入图像。因此，需要一组样本输入来量化这些层并识别最小/最大范围。这样的样本输入称为校准/代表性数据集。

为了将 TensorFlow 浮点模型量化为 TensorFlow Lite 量化模型，TensorFlow Lite 模型提供了训练后量化技术。有关详细信息，参见[训练后量化](https://www.tensorflow.org/lite/performance/post_training_quantization)。

## 训练后量化

TensorFlow Lite 支持两种类型的训练后量化：

- 训练后动态范围量化
- 训练后全整数量化

## 训练后动态范围量化

在训练后动态范围量化中，权重和偏差从浮点精度静态量化为定点整数 8 位精度。激活层范围保持 32 位浮点精度。

为了减少推理过程中的延迟，动态范围运算符执行以下操作：

- 根据激活的范围将其量化为定点整数 8 位精度
- 使用 8 位权重和激活执行计算

Note: 由于仅量化了权重，因此此步骤不需要额外的校准数据。

以下脚本将 TensorFlow 模型转换并量化为 TensorFlow Lite 模型：

    import tensorflow as tf
    from tensorflow import keras
      
    converter = tf.lite.TFLiteConverter.from_saved_model(exp_model_path)
    converter.target_spec.supported_ops = [tf.lite.OpsSet.TFLITE_BUILTINS]
    converter.optimizations = []
      
    tflite_model = converter.convert()
    save_name = 'quantized_model.tflite'
     
    print('Saving Dynamic Quantized TFLite model ..................')
      
    with open(save_name, 'wb') as f:
        f.write(tflite_model)
    Copy to clipboard

## 训练后全整数量化

在全整数量化中，使用代表性数据集对模型内的激活层进行量化。

以下脚本将 TensorFlow 模型转换并量化为 TensorFlow Lite 模型：

    import tensorflow as tf
      
    def representative_dataset():
        for data in dataset:
            yield {
                "image": data.image,
                "bias": data.bias,
            }
    saved_model_dir = “/path/to/saved/model”
      
    # prepare converter by loading model in saved_model format.
    converter = tf.lite.TFLiteConverter.from_saved_model(saved_model_dir)
    converter.optimizations = [tf.lite.Optimize.DEFAULT]
    
    # Set representative dataset used for quantization.
    converter.representative_dataset = representative_dataset
    
    # For full-integer quantization, set target_spec supported_ops to TFLITE_BUILTINS_INT8.
    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
    
    # Convert model
    tflite_quant_model = converter.convert()
    save_name = 'quantized_model_int8.tflite'
     
    print('Saving Quantized TFLite model ..................')
      
    with open(save_name, 'wb') as f:
        f.write(tflite_model)
    Copy to clipboard

Note: 转换器 `target_spec` 中的 `supported_ops` 设置为 `tf.lite.OpsSet.TFLITE_BUILTINS_INT8`。

该脚本生成一个全整数量化模型，更适合定点整数硬件，例如 Qualcomm® RB3 Gen 2 平台上的 Hexagon Tensor Processor。

**Parent Topic:** [将 TensorFlow 或 Keras 模型转换为 TensorFlow Lite 格式](https://docs.qualcomm.com/doc/80-70014-54Y/topic/convert-a-tensorflow-or-keras-model-to-tensorflow-lite-format.html)

Last Published: Aug 06, 2024

[Previous Topic
将 TensorFlow 或 Keras 模型转换为 TensorFlow Lite 格式](https://docs.qualcomm.com/bundle/publicresource/80-70014-54Y/topics/convert-a-tensorflow-or-keras-model-to-tensorflow-lite-format.md) [Next Topic
使用离线转换工具 (CLI) 进行转换](https://docs.qualcomm.com/bundle/publicresource/80-70014-54Y/topics/convert-using-offline-converter-tool-cli.md)