TensorFlow Lite:移动与边缘设备部署

FreeGuideOnline 最新 2026-07-02

python import tensorflow as tf

转换 SavedModel

converter = tf.lite.TFLiteConverter.from_saved_model("saved_model_dir") tflite_model = converter.convert()

保存模型

with open("model.tflite", "wb") as f: f.write(tflite_model)


对于 Keras 模型:
```python
converter = tf.lite.TFLiteConverter.from_keras_model(model)
tflite_model = converter.convert()

固定输入形状以提升性能

默认情况下转换的模型可能包含动态形状,移动端推理时需要额外开销。建议在转换前通过签名或 tf.function 固定输入尺寸,或设置 converter.optimizations 后使用 tf.lite.Optimize

量化与模型优化

为了进一步减小模型体积、加快推理速度,并且充分利用移动设备上的定点运算单元(如 DSP、NPU),必须对模型进行量化。

训练后量化(Post-Training Quantization)

最简单的方式是直接在转换时加入优化选项。

动态范围量化(float32 权重 → float16/int8)

converter = tf.lite.TFLiteConverter.from_saved_model("saved_model_dir")
converter.optimizations = [tf.lite.Optimize.DEFAULT]
tflite_quant_model = converter.convert()

此方法将模型参数量化为 int8/hybrid,但激活值仍以 float32 运行。模型尺寸可减少约 4 倍,推理速度提升 2~3 倍。

全整数量化(Full Integer Quantization) 需要提供代表性数据集(representative dataset)来校准激活值的范围。

def representative_dataset():
    for _ in range(100):
        data = np.random.rand(1, 224, 224, 3).astype(np.float32)
        yield [data]

converter = tf.lite.TFLiteConverter.from_saved_model("saved_model_dir")
converter.optimizations = [tf.lite.Optimize.DEFAULT]
converter.representative_dataset = representative_dataset
converter.target_spec.supported_ops = [tf.lite.OpsSet.TFLITE_BUILTINS_INT8]
converter.inference_input_type = tf.uint8
converter.inference_output_type = tf.uint8
tflite_quant_model = converter.convert()

此种量化使整个网络都以 int8 计算,尺寸缩小到原模型的 1/4,且可以利用硬件加速器。

量化感知训练(Quantization-Aware Training, QAT)

QAT 在训练时模拟量化误差,可获得比训练后量化更高的精度。适用于对精度敏感的模型。

import tensorflow_model_optimization as tfmot

qat_model = tfmot.quantization.keras.quantize_model(base_model)
# ... 重新训练或微调 ...
converter = tf.lite.TFLiteConverter.from_keras_model(qat_model)
converter.optimizations = [tf.lite.Optimize.DEFAULT]
tflite_qat_model = converter.convert()

Float16 量化

适合 GPU 加速,无需校准数据。

converter.optimizations = [tf.lite.Optimize.DEFAULT]
converter.target_spec.supported_types = [tf.float16]

Android 端集成 TensorFlow Lite

添加依赖

app/build.gradle 中加入 TFLite 依赖:

dependencies {
    implementation 'org.tensorflow:tensorflow-lite:2.14.0'
    // 可选 GPU 代理
    implementation 'org.tensorflow:tensorflow-lite-gpu:2.14.0'
    // 可选 NNAPI 代理
    implementation 'org.tensorflow:tensorflow-lite-support:0.4.4'
}

加载模型与构建解释器

.tflite 文件放入 assets 目录,使用 Interpreter 加载。

try {
    Interpreter tflite = new Interpreter(loadModelFile());
} catch (Exception e) {
    e.printStackTrace();
}

// 辅助方法
private ByteBuffer loadModelFile() throws IOException {
    AssetFileDescriptor fileDescriptor = context.getAssets().openFd("model.tflite");
    FileInputStream inputStream = new FileInputStream(fileDescriptor.getFileDescriptor());
    FileChannel fileChannel = inputStream.getChannel();
    long startOffset = fileDescriptor.getStartOffset();
    long declaredLength = fileDescriptor.getDeclaredLength();
    return fileChannel.map(FileChannel.MapMode.READ_ONLY, startOffset, declaredLength);
}

执行推理

准备输入张量,调用 run() 方法。

// 获取输入输出信息
int inputShape[] = tflite.getInputTensor(0).shape();
DataType inputType = tflite.getInputTensor(0).dataType();
// 根据类型分配输入缓冲区,此处假设输入为 float32,尺寸 [1, 224, 224, 3]
ByteBuffer inputBuffer = ByteBuffer.allocateDirect(4 * inputShape[1] * inputShape[2] * inputShape[3]);
inputBuffer.order(ByteOrder.nativeOrder());
// 将预处理后的图像数据写入 inputBuffer...

// 分配输出缓冲区
int outputShape[] = tflite.getOutputTensor(0).shape();
ByteBuffer outputBuffer = ByteBuffer.allocateDirect(4 * outputShape[1]);
outputBuffer.order(ByteOrder.nativeOrder());

// 推理
tflite.run(inputBuffer, outputBuffer);
// 解析输出结果

使用 Android GPU 代理

GPU 代理可显著提高推理速度,尤其适用于视觉模型。替换解释器创建方式。

GpuDelegate delegate = new GpuDelegate();
Interpreter.Options options = new Interpreter.Options().addDelegate(delegate);
Interpreter tflite = new Interpreter(loadModelFile(), options);

使用 NNAPI 代理(Android Neural Networks API)

NNAPI 利用 DSP、NPU 等专用芯片。在 Android 8.1 及以上可用。

Interpreter.Options options = new Interpreter.Options();
options.setUseNNAPI(true);
Interpreter tflite = new Interpreter(loadModelFile(), options);

iOS 端集成 TensorFlow Lite

安装 TFLite 框架

通过 CocoaPods 添加依赖到 Podfile

target 'YourApp' do
  pod 'TensorFlowLiteSwift'  # Swift 版本
  # 或 C API: pod 'TensorFlowLiteC'
end

运行 pod install

Swift 示例代码

导入模块并加载模型。

import TensorFlowLite

guard let modelPath = Bundle.main.path(forResource: "model", ofType: "tflite") else {
    // 处理错误
    return
}
var options = Interpreter.Options()
// 可选:启用 GPU 代理
if let delegate = MetalDelegate() {
    options = Interpreter.Options(delegates: [delegate])
}
let interpreter = try Interpreter(modelPath: modelPath, options: options)
try interpreter.allocateTensors()

输入输出处理:

// 获取输入张量
let inputDetails = try interpreter.input(at: 0)
// 准备输入数据(通常为 Data 类型)
let inputData: Data = // 预处理后的图像数据
try interpreter.copy(inputData, toInputAt: 0)

// 执行推理
try interpreter.invoke()

// 读取输出
let outputTensor = try interpreter.output(at: 0)
let output = [Float](unsafeData: outputTensor.data) ?? []

使用 GPU Metal 代理

iOS 上 GPU 代理基于 Metal,适用于图像密集任务。

guard let metalDelegate = MetalDelegate() else {
    fatalError("Metal delegate not available")
}
let interpreter = try Interpreter(modelPath: modelPath, delegates: [metalDelegate])

使用 Core ML 代理(将 TFLite 模型进一步转换为 Core ML)

TensorFlow Lite 也可以通过 Core ML Delegate 利用 Apple Neural Engine 加速。需使用 TensorFlowLiteSwift 框架的 CoreMLDelegate(iOS 11+)。

模型验证与性能测试

在正式集成前,建议使用 benchmark_model 工具测量推理耗时和内存占用。可在 Android 设备上通过 adb 直接运行:

adb shell /data/local/tmp/benchmark_model \
  --graph=/data/local/tmp/model.tflite \
  --num_threads=4 \
  --use_gpu=true