スポンサーリンク

【Tensorflow Lite】interpreterの役割と処理のご紹介。

TensorFlow
スポンサーリンク

今回の記事は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の説明。

他にも機械学習関連の記事もたくさんあるので是非参考にしてください。

本記事を読んでいただき感謝です。サイトを訪れていただいた方はプログラミング勉強中かと思いますのでプログラミング勉強のコツを合わせてご紹介。

スポンサーリンク
スポンサーリンク
スポンサーリンク

ブログに関しては500円程度かかりますが、それ以外は無料です。知識の吸収と並行してアウトプットは非常に効率が良いです。テックアカデミーに関しては講座レベルが高いにも関わらず、無料体験や人気口座も大幅値下げがあるので、重点的に学びたいものを無料体験してみてください。

転職時にも、エンジニアからテックアカデミー・Paizaは認知度が高いので、未経験入社採用を行う際履歴書で目に留まります。特にPaizaのスキルレベルA・SなどはIT業界でも評価されます。

テックアカデミー・Paizaの無料登録ができる期間中にぜひご利用してみてください。私も活用経験ありです。

TensorFlow
スポンサーリンク
スポンサーリンク
ともぶろぐ

コメント

タイトルとURLをコピーしました