gpt4 book ai didi

python - 在 python 中加载 Tensorflow Lite 模型

转载 作者:行者123 更新时间:2023-12-03 08:20:00 55 4
gpt4 key购买 nike

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

保存和加载“正常” tensorflow 模型

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

最佳答案

您可以使用tflite interpreter直接在笔记本中从 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。

关于python - 在 python 中加载 Tensorflow Lite 模型,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/68132431/

55 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com