如何在脚本中加载tflite模型?

Har*_*hra 7 python tensorflow tensorflow-lite

我已经使用bazel.pbtflite文件转换为文件。现在,我想在我的python脚本中加载此模型,只是为了测试天气是否为我提供了正确的输出?tflite

Jin*_*hao 23

您可以使用TensorFlow Lite Python解释器将tflite模型加载到python shell中,并使用输入数据对其进行测试。

代码将如下所示:

import numpy as np
import tensorflow as tf

# Load TFLite model and allocate tensors.
interpreter = tf.lite.Interpreter(model_path="converted_model.tflite")
interpreter.allocate_tensors()

# Get input and output tensors.
input_details = interpreter.get_input_details()
output_details = interpreter.get_output_details()

# Test model on random input data.
input_shape = input_details[0]['shape']
input_data = np.array(np.random.random_sample(input_shape), dtype=np.float32)
interpreter.set_tensor(input_details[0]['index'], input_data)

interpreter.invoke()

# The function `get_tensor()` returns a copy of the tensor data.
# Use `tensor()` in order to get a pointer to the tensor.
output_data = interpreter.get_tensor(output_details[0]['index'])
print(output_data)
Run Code Online (Sandbox Code Playgroud)

上面的代码来自TensorFlow Lite官方指南有关更多详细信息,请阅读此内容

  • 如何对测试数据进行测试而不是随机数据 (3认同)

Ben*_*rth 5

在 Python 中使用 TensorFlow lite 模型:

TensorFlow Lite 的冗长功能非常强大,因为它允许您进行更多控制,但在许多情况下您只想传递输入并获取输出,因此我创建了一个包含此逻辑的类:

以下适用于 tfhub.dev 的分类模型,例如: https: //tfhub.dev/tensorflow/lite-model/mobilenet_v2_1.0_224/1/metadata/1

# Usage
model = TensorflowLiteClassificationModel("path/to/model.tflite")
(label, probability) = model.run_from_filepath("path/to/image.jpeg")
Run Code Online (Sandbox Code Playgroud)
import tensorflow as tf
import numpy as np
from PIL import Image


class TensorflowLiteClassificationModel:
    def __init__(self, model_path, labels, image_size=224):
        self.interpreter = tf.lite.Interpreter(model_path=model_path)
        self.interpreter.allocate_tensors()
        self._input_details = self.interpreter.get_input_details()
        self._output_details = self.interpreter.get_output_details()
        self.labels = labels
        self.image_size=image_size

    def run_from_filepath(self, image_path):
        input_data_type = self._input_details[0]["dtype"]
        image = np.array(Image.open(image_path).resize((self.image_size, self.image_size)), dtype=input_data_type)
        if input_data_type == np.float32:
            image = image / 255.

        if image.shape == (1, 224, 224):
            image = np.stack(image*3, axis=0)

        return self.run(image)

    def run(self, image):
        """
        args:
          image: a (1, image_size, image_size, 3) np.array

        Returns list of [Label, Probability], of type List<str, float>
        """

        self.interpreter.set_tensor(self._input_details[0]["index"], image)
        self.interpreter.invoke()
        tflite_interpreter_output = self.interpreter.get_tensor(self._output_details[0]["index"])
        probabilities = np.array(tflite_interpreter_output[0])

        # create list of ["label", probability], ordered descending probability
        label_to_probabilities = []
        for i, probability in enumerate(probabilities):
            label_to_probabilities.append([self.labels[i], float(probability)])
        return sorted(label_to_probabilities, key=lambda element: element[1])
Run Code Online (Sandbox Code Playgroud)

警告

但是,您需要修改它以支持不同的用例,因为我将图像作为输入传递,并获取分类([标签,概率])输出。如果您需要文本输入(NLP)或其他输出(对象检测输出边界框、标签和概率)、分类(仅标签)等)。

另外,如果您期望不同尺寸的图像输入,那么您必须更改输入尺寸并重新分配模型 ( self.interpreter.allocate_tensors())。这很慢(效率低下)。最好使用平台调整大小功能(例如 Android 图形库),而不是使用 TensorFlow lite 模型来进行调整大小。或者,您可以使用单独的模型来调整模型的大小,这会更快allocate_tensors()