在 python 中加载 Tensorflow Lite 模型

问题描述 投票:0回答:1

我正在开发一个 TinyML 项目,使用 Tensorflow Lite 以及量化模型和浮点模型。在我的管道中,我使用

tf.keras
API 训练模型,然后将模型转换为 TFLite 模型。最后,我将 TFLite 模型量化为 int8。
我可以使用 API
model.save
tf.keras.model.load_model

保存和加载“正常”张量流模型

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

python tensorflow tensorflow-lite tinyml
1个回答
5
投票

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

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

tflite_model_file = 'converted_model.tflite'

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

# 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)

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

© www.soinside.com 2019 - 2024. All rights reserved.