在 python 中加载 Tensorflow Lite 模型

Yax*_*xit 2 python tensorflow tensorflow-lite tinyml

我正在开发一个 TinyML 项目,使用 Tensorflow Lite 以及量化模型和浮点模型。在我的管道中,我使用 API 训练模型tf.keras,然后将模型转换为 TFLite 模型。最后,我将 TFLite 模型量化为 int8。我可以使用API
保存和加载“正常”张量流模型model.savetf.keras.model.load_model

是否可以对转换后的 TFLite 模型执行相同的操作?每次都要经历量化过程是相当耗时的。

Kav*_*veh 5

您可以使用tflite 解释器直接在笔记本中从 TFLite 模型进行推理。

这是图像分类模型的示例。假设我们有一个 tflite 模型:

tflite_model_file = 'converted_model.tflite'
Run Code Online (Sandbox Code Playgroud)

然后我们可以像这样加载和测试它:

# Load TFLite model and allocate tensors.
with open(tflite_model_file, 'rb') as fid:
    tflite_model = fid.read()
    
interpreter = tf.lite.Interpreter(model_content=tflite_model)
interpreter.allocate_tensors()

input_index = interpreter.get_input_details()[0]["index"]
output_index = interpreter.get_output_details()[0]["index"]

# Gather results for the randomly sampled test images
predictions = []

test_labels, test_imgs = [], []
for img, label in tqdm(test_batches.take(10)):
    interpreter.set_tensor(input_index, img)
    interpreter.invoke()
    predictions.append(interpreter.get_tensor(output_index))
    
    test_labels.append(label.numpy()[0])
    test_imgs.append(img)
Run Code Online (Sandbox Code Playgroud)

请注意,您只能从 tflite 模型进行推断。您无法更改架构和层,例如重新加载 Keras 模型。如果你想改变架构,你应该保存Keras模型,并测试它,直到得到满意的结果,然后将其转换为tflite。