エッジAIとは、クラウドではなく端末(エッジデバイス)上で直接AI推論を実行します技術のことです。スマートフォン、IoTデバイス、組み込み機器など、リソースが限られた環境でAIモデルを動作させることで、低レイテンシ、プライバシー保護、オフライン動作といった利点を得られる。
筆者がエッジAIに本格的に取り組み始めたのは、工場の検品システムを開発した案件がきっかけだった。ネットワーク遅延が許容できないリアルタイム検査において、クラウド推論は選択肢にならなかった。その経験を踏まえ、TensorFlow Liteを使ったオンデバイス推論の実践的な入門ガイドをお届けします。
TensorFlow Lite(以下TFLite)は、GoogleがモバイルおよびIoTデバイス向けに開発した軽量推論フレームワークです。通常のTensorFlowモデルを最適化・変換し、リソース制約のある環境で効率的に実行できます。
まず、学習済みのTensorFlowモデルをTFLite形式に変換する方法を見ていこう。
import tensorflow as tf
# 学習済みモデルの読み込み
model = tf.keras.models.load_model('my_model.h5')
# 基本的な変換
converter = tf.lite.TFLiteConverter.from_keras_model(model)
tflite_model = converter.convert()
# .tfliteファイルとして保存
with open('model.tflite', 'wb') as f:
f.write(tflite_model)
print(f"モデルサイズ: {len(tflite_model) / 1024 / 1024:.2f} MB")
基本的な変換はこれだけで完了します。しかし、実務ではモデルサイズとレイテンシの削減が求められるため、量子化が不可欠だ。
量子化は、モデルの重みと活性化関数の値をFloat32からINT8などの低精度表現に変換する技術だ。モデルサイズを最大4分の1に圧縮し、推論速度も大幅に向上します。
import tensorflow as tf
import numpy as np
# ダイナミックレンジ量子化(最も手軽)
converter = tf.lite.TFLiteConverter.from_keras_model(model)
converter.optimizations = [tf.lite.Optimize.DEFAULT]
tflite_dynamic = converter.convert()
print(f"ダイナミック量子化後: {len(tflite_dynamic) / 1024 / 1024:.2f} MB")
# フル整数量子化(最も高い圧縮率・高速化)
def representative_dataset():
"""キャリブレーション用の代表データを提供"""
for _ in range(100):
data = np.random.rand(1, 224, 224, 3).astype(np.float32)
yield [data]
converter_full = tf.lite.TFLiteConverter.from_keras_model(model)
converter_full.optimizations = [tf.lite.Optimize.DEFAULT]
converter_full.representative_dataset = representative_dataset
converter_full.target_spec.supported_ops = [
tf.lite.OpsSet.TFLITE_BUILTINS_INT8
]
converter_full.inference_input_type = tf.uint8
converter_full.inference_output_type = tf.uint8
tflite_full_int = converter_full.convert()
print(f"フル整数量子化後: {len(tflite_full_int) / 1024 / 1024:.2f} MB")
筆者の経験では、画像分類モデルの場合、フル整数量子化により精度の低下は1〜2%程度に抑えられることが多いです。この精度低下がユースケースで許容できるかどうかを事前に検証することが重要だ。
変換したモデルを使って推論を実行するコードは以下の通りです。
import numpy as np
import tensorflow as tf
from PIL import Image
# TFLiteインタープリターの初期化
interpreter = tf.lite.Interpreter(model_path='model.tflite')
interpreter.allocate_tensors()
# 入出力のテンソル情報を取得
input_details = interpreter.get_input_details()
output_details = interpreter.get_output_details()
# 画像の前処理
image = Image.open('test_image.jpg').resize((224, 224))
input_data = np.expand_dims(np.array(image, dtype=np.float32) / 255.0, axis=0)
# 推論の実行
interpreter.set_tensor(input_details[0]['index'], input_data)
interpreter.invoke()
# 結果の取得
output_data = interpreter.get_tensor(output_details[0]['index'])
predicted_class = np.argmax(output_data[0])
confidence = np.max(output_data[0])
print(f"予測クラス: {predicted_class}, 信頼度: {confidence:.4f}")
エッジAIの代表的なデプロイ先であるRaspberry Piでの実行について述べる。Raspberry Pi 4以降であれば、画像分類モデルをリアルタイムに近い速度で実行できます。
# Raspberry PiへのTFLiteランタイムインストール
# pip install tflite-runtime
import tflite_runtime.interpreter as tflite
import time
# tflite-runtimeを使用(軽量版)
interpreter = tflite.Interpreter(model_path='model.tflite')
interpreter.allocate_tensors()
# ベンチマーク
times = []
for i in range(100):
start = time.perf_counter()
interpreter.set_tensor(input_details[0]['index'], input_data)
interpreter.invoke()
elapsed = (time.perf_counter() - start) * 1000
times.append(elapsed)
print(f"平均推論時間: {np.mean(times):.1f}ms")
print(f"中央値: {np.median(times):.1f}ms")
print(f"95パーセンタイル: {np.percentile(times, 95):.1f}ms")
筆者の環境(Raspberry Pi 4 Model B、4GB RAM)では、MobileNetV2の量子化モデルで平均推論時間は約30ms程度だった。これはリアルタイムの画像分類には十分な速度だ。
エッジAIの導入にあたり、筆者が実務で直面した課題と対策を共有します。
TensorFlow Liteは、エッジAI入門として最も手軽で実用的な選択肢だ。学習済みモデルの変換から量子化、デバイスへのデプロイまで、一貫したワークフローが整備されています。まずはシンプルな画像分類から始めて、徐々に物体検出や異常検知といったより高度なユースケースに挑戦することをお勧めします。エッジAIの需要は今後さらに拡大することは確実であり、今のうちに実践的なスキルを身につけておく価値は大きいです。