تبدیل مدل های TensorFlow

این صفحه نحوه تبدیل یک مدل TensorFlow به یک مدل TensorFlow Lite (فرمت FlatBuffer بهینه شده که با پسوند فایل .tflite شناسایی می شود) را با استفاده از مبدل TensorFlow Lite شرح می دهد.

گردش کار تبدیل

نمودار زیر روند کار سطح بالا برای تبدیل مدل شما را نشان می دهد:

گردش کار مبدل TFLite

شکل 1. گردش کار مبدل.

می توانید مدل خود را با استفاده از یکی از گزینه های زیر تبدیل کنید:

  1. Python API ( توصیه می شود ): این به شما امکان می دهد تبدیل را در خط لوله توسعه خود ادغام کنید، بهینه سازی ها را اعمال کنید، ابرداده ها را اضافه کنید و بسیاری از کارهای دیگر که فرآیند تبدیل را ساده می کند.
  2. خط فرمان : این فقط از تبدیل مدل اولیه پشتیبانی می کند.

Python API

کد راهنما: برای کسب اطلاعات بیشتر در مورد API مبدل TensorFlow Lite، print(help(tf.lite.TFLiteConverter)) را اجرا کنید.

یک مدل TensorFlow را با استفاده از tf.lite.TFLiteConverter تبدیل کنید. یک مدل TensorFlow با استفاده از قالب SavedModel ذخیره می‌شود و یا با استفاده از APIهای سطح بالا tf.keras.* (یک مدل Keras) یا سطح پایین tf.* API (که از آنها توابع مشخصی تولید می‌کنید) تولید می‌شود. در نتیجه، شما سه گزینه زیر را دارید (نمونه ها در چند بخش بعدی هستند):

مثال زیر نحوه تبدیل SavedModel به یک مدل TensorFlow Lite را نشان می دهد.

import tensorflow as tf

# Convert the model
converter = tf.lite.TFLiteConverter.from_saved_model(saved_model_dir) # path to the SavedModel directory
tflite_model = converter.convert()

# Save the model.
with open('model.tflite', 'wb') as f:
  f.write(tflite_model)

تبدیل مدل کراس

مثال زیر نحوه تبدیل یک مدل Keras را به یک مدل TensorFlow Lite نشان می دهد.

import tensorflow as tf

# Create a model using high-level tf.keras.* APIs
model = tf.keras.models.Sequential([
    tf.keras.layers.Dense(units=1, input_shape=[1]),
    tf.keras.layers.Dense(units=16, activation='relu'),
    tf.keras.layers.Dense(units=1)
])
model.compile(optimizer='sgd', loss='mean_squared_error') # compile the model
model.fit(x=[-1, 0, 1], y=[-3, -1, 1], epochs=5) # train the model
# (to generate a SavedModel) tf.saved_model.save(model, "saved_model_keras_dir")

# Convert the model.
converter = tf.lite.TFLiteConverter.from_keras_model(model)
tflite_model = converter.convert()

# Save the model.
with open('model.tflite', 'wb') as f:
  f.write(tflite_model)

تبدیل توابع بتن

مثال زیر نحوه تبدیل توابع بتن را به یک مدل TensorFlow Lite نشان می دهد.

import tensorflow as tf

# Create a model using low-level tf.* APIs
class Squared(tf.Module):
  @tf.function(input_signature=[tf.TensorSpec(shape=[None], dtype=tf.float32)])
  def __call__(self, x):
    return tf.square(x)
model = Squared()
# (ro run your model) result = Squared(5.0) # This prints "25.0"
# (to generate a SavedModel) tf.saved_model.save(model, "saved_model_tf_dir")
concrete_func = model.__call__.get_concrete_function()

# Convert the model.

converter = tf.lite.TFLiteConverter.from_concrete_functions([concrete_func],
                                                            model)
tflite_model = converter.convert()

# Save the model.
with open('model.tflite', 'wb') as f:
  f.write(tflite_model)

ویژگی های دیگر

  • بهینه سازی ها را اعمال کنید. یک بهینه سازی رایج مورد استفاده، کوانتیزاسیون پس از آموزش است که می تواند تأخیر و اندازه مدل شما را با حداقل کاهش دقت کاهش دهد.

  • ابرداده را اضافه کنید، که باعث می‌شود هنگام استقرار مدل‌ها در دستگاه‌ها، کد بسته‌بندی خاص پلتفرم ایجاد کنید.

خطاهای تبدیل

خطاهای رایج تبدیل و راه حل های زیر به شرح زیر است:

ابزار خط فرمان

اگر TensorFlow 2.x را از پیپ نصب کرده اید، از دستور tflite_convert استفاده کنید. برای مشاهده تمام پرچم های موجود، از دستور زیر استفاده کنید:

$ tflite_convert --help

`--output_file`. Type: string. Full path of the output file.
`--saved_model_dir`. Type: string. Full path to the SavedModel directory.
`--keras_model_file`. Type: string. Full path to the Keras H5 model file.
`--enable_v1_converter`. Type: bool. (default False) Enables the converter and flags used in TF 1.x instead of TF 2.x.

You are required to provide the `--output_file` flag and either the `--saved_model_dir` or `--keras_model_file` flag.

اگر منبع TensorFlow 2.x را دانلود کرده‌اید و می‌خواهید مبدل را از آن منبع بدون ساخت و نصب بسته اجرا کنید، می‌توانید « tflite_convert » را با « bazel run tensorflow/lite/python:tflite_convert -- » در دستور جایگزین کنید.

تبدیل SavedModel

tflite_convert \
  --saved_model_dir=/tmp/mobilenet_saved_model \
  --output_file=/tmp/mobilenet.tflite

تبدیل مدل Keras H5

tflite_convert \
  --keras_model_file=/tmp/mobilenet_keras_model.h5 \
  --output_file=/tmp/mobilenet.tflite

مراحل بعدی

از مفسر TensorFlow Lite برای اجرای استنتاج در دستگاه مشتری (مثلاً تلفن همراه، جاسازی شده) استفاده کنید.