הממיר לייט TensorFlow לוקח מודל TensorFlow ומייצר מודל לייט TensorFlow (בלתי מותאם FlatBuffer בפורמט שזוהו על ידי .tflite
סיומת הקובץ). יש לך את שתי האפשרויות הבאות לשימוש בממיר:
- Python API (מומלץ): זה מקל כדי להמיר דגמים כחלק בצנרת פיתוח מודל, ליישם אופטימיזציות, להוסיף metadata ויש לו תכונות רבות נוספות.
- שורת פקודה : זה רק תומך מרת מודל בסיסית.
API של Python
קוד Helper: כדי לזהות את גרסת TensorFlow המותקנת, לרוץ print(tf.__version__)
וכדי ללמוד עוד על ה- API ממיר TensorFlow לייט, ריצת print(help(tf.lite.TFLiteConverter))
.
אם כבר מותקנת 2.x TensorFlow , יש לך את שתי האפשרויות הבאות: (אם כבר מותקן 1.x TensorFlow , מתייחסים Github )
המרת מודל 2.x TensorFlow באמצעות
tf.lite.TFLiteConverter
. TensorFlow מודל 2.x מאוחסן באמצעות פורמט SavedModel ו נוצר גם באמצעות ברמה הגבוההtf.keras.*
APIs (מודל Keras) או ברמה הנמוכהtf.*
APIs (שממנו אתה יוצר פונקציות בטון). כתוצאה מכך, עומדות בפניך שלוש האפשרויות הבאות (דוגמאות נמצאות בסעיפים הבאים):-
tf.lite.TFLiteConverter.from_saved_model()
(מומלץ): הממיר SavedModel . -
tf.lite.TFLiteConverter.from_keras_model()
: הממיר Keras מודל. -
tf.lite.TFLiteConverter.from_concrete_functions()
: המרת פונקציות בטון .
-
המרת מודל 1.x TensorFlow באמצעות
tf.compat.v1.lite.TFLiteConverter
(הדוגמאות הן על Github ):-
tf.compat.v1.lite.TFLiteConverter.from_saved_model()
: הממיר SavedModel . -
tf.compat.v1.lite.TFLiteConverter.from_keras_model_file()
: הממיר Keras מודל. -
tf.compat.v1.lite.TFLiteConverter.from_session()
: ממיר GraphDef מהפעלה. -
tf.compat.v1.lite.TFLiteConverter.from_frozen_graph()
: ממיר קפוא GraphDef מקובץ. אם יש לך מחסומים, אז קודם להמיר אותו לקובץ הקפוא GraphDef ולאחר מכן להשתמש ב- API זה כמוצג כאן .
-
המר SavedModel (מומלץ)
מופעי דוגמא הבאים כיצד להמיר SavedModel למודל לייט TensorFlow.
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
מופעי דוגמה הבאים כיצד להמיר Keras מודל למודל לייט TensorFlow.
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.
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.
# Notes that for the versions earlier than TensorFlow 2.7, the
# from_concrete_functions API is able to work when there is only the first
# argument given:
# > converter = tf.lite.TFLiteConverter.from_concrete_functions([concrete_func])
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)
תכונות אחרות
החל אופטימיזציות . אופטימיזציה נפוצה היא קוונטיזציה הכשרת פוסט , אשר יכול לצמצם עוד יותר את זמן אחזור המודל שלך וגדל עם הפסד מינימאלי ודיוק.
הוספת metadata , מה שהופך אותו קל יותר ליצור קוד מעטפת פלטפורמה ספציפית כאשר פריסת מודלים בהתקנים.
שגיאות המרה
להלן שגיאות המרה נפוצות והפתרונות שלהן:
שגיאה:
Some ops are not supported by the native TFLite runtime, you can enable TF kernels fallback using TF Select. See instructions: <a href="https://www.tensorflow.org/lite/guide/ops_select">https://www.tensorflow.org/lite/guide/ops_select</a> TF Select ops: ..., .., ...
פתרון: השגיאה מתרחשת מכיוון שלדגם שלך יש TF ops שאין להם מימוש TFLite תואם. ניתן לפתור זאת על ידי שימוש אופ TF במודל TFLite (מומלץ). אם אתה רוצה ליצור מודל עם ops TFLite בלבד, אתה יכול גם להוסיף בקשה עבור אופ TFLite חסר הנושא Github # 21,526 (להשאיר תגובה אם בקשתך לא כבר הוזכר) או ליצור את אופ TFLite עצמך.
שגיאה:
.. is neither a custom op nor a flex op
פתרון: אם TF אופציה זו היא:
נתמך ב TF: השגיאה מתרחשת משום אופ TF חסרה allowlist (רשימה ממצה של חיילי מיחידות TF הנתמכת על ידי TFLite). אתה יכול לפתור זאת באופן הבא:
לא נתמך ב-TF: השגיאה מתרחשת מכיוון ש- TFLite לא מודע לאופרטור TF המותאם אישית שהוגדר על ידך. אתה יכול לפתור זאת באופן הבא:
- צור את אופ TF .
- המרת המודל TF למודל TFLite .
- צור את אופ TFLite והסקה מנוהלת על ידי קשירתו ריצת TFLite.
כלי שורת הפקודה
מומלץ מאוד כי אתה משתמש ב- API Python רשום למעלה, אם אפשר.
אם כבר מותקנת TensorFlow 2.x מן PIP , להשתמש tflite_convert
הפקודה כדלקמן: (אם כבר מותקן 2.x TensorFlow ממקור אז אתה יכול להחליף את " tflite_convert
" עם ' bazel run //tensorflow/lite/python:tflite_convert --
'בסעיפים הבאים, ואם אתה כבר מותקן 1.x TensorFlow אז מתייחסים Github ( הפניה , דוגמאות ))
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.
המרת 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 כדי היקש לרוץ על מכשיר הלקוח (למשל ניידים, מוטבע).