今回の記事はPythonの機械学習でエッジ用に利用されるTensorFlowLiteで使用する「interpreter」というメソッドを使用する方法に関してご紹介します。分かりやすく解説しますので是非参考にしてみてください。
Tensorflow Liteのinterpreterの役割
interpreterは簡単にいうとTensorflowLiteを使用する際のラッパークラスで、使用する対象のデータ(テンソル)をセットするのと学習モデルをセット、その学習モデルを動作させ、出力を取得するメソッドの大きく分けて4つの役割があります。
import numpy as np
import tensorflow as tf
from PIL import Image
import numpy as np
# Load the TFLite model and allocate tensors.
interpreter = tf.lite.Interpreter(model_path="[モデルパス].tflite")
interpreter.allocate_tensors()
# Get input and output tensors.
input_details = interpreter.get_input_details()
output_details = interpreter.get_output_details()
# Test the model on random input data.
input_shape = input_details[0]['shape']
image_size = 50
file = "[識別画像パス].JPG"
image = Image.open(file)
image = image.convert("RGB")
image = image.resize((image_size, image_size))
data = np.asarray(image)
data = data[ np.newaxis,:, :, :]
input_data = np.array(data, 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'])
では簡単にコードの説明に進みます。
まず、下記でAIモデルのセットを行います。
# Load the TFLite model and allocate tensors.
interpreter = tf.lite.Interpreter(model_path="[モデルパス].tflite")
interpreter.allocate_tensors()
次に識別するデータの形式と出力のデータ形式を決定し、識別データをセットします。
# Get input and output tensors.
input_details = interpreter.get_input_details()
output_details = interpreter.get_output_details()
# Test the model on random input data.
input_shape = input_details[0]['shape']
image_size = 50
file = "[識別画像パス].JPG"
image = Image.open(file)
image = image.convert("RGB")
image = image.resize((image_size, image_size))
data = np.asarray(image)
data = data[ np.newaxis,:, :, :]
input_data = np.array(data, 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)
以上で今回の記事は終了です。他にもTensorflowLiteを用いたObjectDetectionAPIに関しての記事を記載しています。
「TensorflowLiteのModeldatahandlerの説明。」
他にも機械学習関連の記事もたくさんあるので是非参考にしてください。
コメント