![]() |
![]() |
![]() |
![]() |
TensorFlow Lite 模型分析器 API 透過列出模型的結構,協助您分析 TensorFlow Lite 格式的模型。
模型分析器 API
以下 API 可用於 TensorFlow Lite 模型分析器。
tf.lite.experimental.Analyzer.analyze(model_path=None,
model_content=None,
gpu_compatibility=False)
您可以從 https://tensorflow.dev.org.tw/api_docs/python/tf/lite/experimental/Analyzer 找到 API 詳細資訊,或從 Python 終端機執行 help(tf.lite.experimental.Analyzer.analyze)
。
簡單 Keras 模型的基礎用法
以下程式碼顯示模型分析器的基礎用法。它顯示轉換後的 Keras 模型在 TFLite 模型內容中的內容,格式為 flatbuffer 物件。
import tensorflow as tf
model = tf.keras.models.Sequential([
tf.keras.layers.Flatten(input_shape=(128, 128)),
tf.keras.layers.Dense(256, activation='relu'),
tf.keras.layers.Dropout(0.2),
tf.keras.layers.Dense(10)
])
fb_model = tf.lite.TFLiteConverter.from_keras_model(model).convert()
tf.lite.experimental.Analyzer.analyze(model_content=fb_model)
MobileNetV3Large Keras 模型的基礎用法
此 API 適用於大型模型,例如 MobileNetV3Large。由於輸出很大,您可能想使用您喜愛的文字編輯器瀏覽它。
model = tf.keras.applications.MobileNetV3Large()
fb_model = tf.lite.TFLiteConverter.from_keras_model(model).convert()
tf.lite.experimental.Analyzer.analyze(model_content=fb_model)
檢查 GPU 委派相容性
ModelAnalyzer API 提供一種方法,透過提供 gpu_compatibility=True
選項來檢查給定模型的 GPU 委派相容性。
案例 1:當模型不相容時
以下程式碼顯示如何針對簡單的 tf.function 使用 gpu_compatibility=True
選項,該函數使用 tf.slice
和 2D 張量以及 tf.cosh
,這些與 GPU 委派不相容。
您會看到每個有相容性問題的節點都有 GPU COMPATIBILITY WARNING
。
import tensorflow as tf
@tf.function(input_signature=[
tf.TensorSpec(shape=[4, 4], dtype=tf.float32)
])
def func(x):
return tf.cosh(x) + tf.slice(x, [1, 1], [1, 1])
converter = tf.lite.TFLiteConverter.from_concrete_functions(
[func.get_concrete_function()], func)
converter.target_spec.supported_ops = [
tf.lite.OpsSet.TFLITE_BUILTINS,
tf.lite.OpsSet.SELECT_TF_OPS,
]
fb_model = converter.convert()
tf.lite.experimental.Analyzer.analyze(model_content=fb_model, gpu_compatibility=True)
案例 2:當模型相容時
在此範例中,給定的模型與 GPU 委派相容。
model = tf.keras.models.Sequential([
tf.keras.layers.Flatten(input_shape=(128, 128)),
tf.keras.layers.Dense(256, activation='relu'),
tf.keras.layers.Dropout(0.2),
tf.keras.layers.Dense(10)
])
fb_model = tf.lite.TFLiteConverter.from_keras_model(model).convert()
tf.lite.experimental.Analyzer.analyze(model_content=fb_model, gpu_compatibility=True)