مشاهده در TensorFlow.org | در Google Colab اجرا شود | مشاهده منبع در GitHub | دانلود دفترچه یادداشت |
TensorFlow Lite (TFLite) مجموعه ای از ابزارهایی است که به توسعه دهندگان کمک می کند استنتاج ML را روی دستگاه (دستگاه های تلفن همراه، جاسازی شده و اینترنت اشیا) اجرا کنند. مبدل TFLite یکی از ابزارهایی است که مدلهای TF موجود را به قالب مدل TFLite بهینهسازی شده تبدیل میکند که میتواند به طور موثر روی دستگاه اجرا شود.
در این سند، می آموزید که چه تغییراتی را باید در کد تبدیل TF به TFLite خود ایجاد کنید، به دنبال آن چند مثال که همین کار را انجام می دهند.
کد تبدیل TF به TFLite شما را تغییر می دهد
اگر از فرمت مدل قدیمی TF1 استفاده می کنید (فایل Keras، GraphDef منجمد، نقاط چک، tf.Session و غیره)، آن را به TF1/TF2 SavedModel به روز کنید و از API مبدل TF2
tf.lite.TFLiteConverter.from_saved_model(...)برای تبدیل آن به مدل TFLite (به جدول 1 مراجعه کنید).پرچم های API مبدل را به روز کنید (به جدول 2 مراجعه کنید).
APIهای قدیمی مانند
tf.lite.constantsرا حذف کنید. (به عنوان مثال:tf.lite.constants.INT8tf.int8کنید)
// جدول 1 // به روز رسانی API مبدل پایتون TFLite
| TF1 API | TF2 API |
|---|---|
tf.lite.TFLiteConverter.from_saved_model('saved_model/',..) | پشتیبانی |
tf.lite.TFLiteConverter.from_keras_model_file('model.h5',..) | حذف شد (بهروزرسانی به فرمت SavedModel) |
tf.lite.TFLiteConverter.from_frozen_graph('model.pb',..) | حذف شد (بهروزرسانی به فرمت SavedModel) |
tf.lite.TFLiteConverter.from_session(sess,...) | حذف شد (بهروزرسانی به فرمت SavedModel) |
// جدول 2 // TFLite Python Converter API Flags Update
| TF1 API | TF2 API |
|---|---|
allow_custom_opsoptimizationsrepresentative_datasettarget_specinference_input_typeinference_output_typeexperimental_new_converterexperimental_new_quantizer | پشتیبانی |
input_tensorsoutput_tensorsinput_arrays_with_shapeoutput_arraysexperimental_debug_info_func | حذف شد (آگومان های API مبدل پشتیبانی نشده) |
change_concat_input_rangesdefault_ranges_statsget_input_arrays()inference_typequantized_input_statsreorder_across_fake_quant | حذف شد (جریان کاری کوانتیزاسیون پشتیبانی نشده) |
conversion_summary_dirdump_graphviz_dirdump_graphviz_video | حذف شد (به جای آن، مدل ها را با استفاده از Netron یا visualize.py تجسم کنید) |
output_formatdrop_control_dependency | حذف شد (ویژگی های پشتیبانی نشده در TF2) |
مثال ها
اکنون نمونه هایی را برای تبدیل مدل های قدیمی TF1 به TF1/TF2 SavedModels و سپس تبدیل آن به مدل های TF2 TFLite ارائه خواهید داد.
برپایی
با واردات TensorFlow لازم شروع کنید.
import tensorflow as tf
import tensorflow.compat.v1 as tf1
import numpy as np
import logging
logger = tf.get_logger()
logger.setLevel(logging.ERROR)
import shutil
def remove_dir(path):
try:
shutil.rmtree(path)
except:
pass
تمام قالب های مدل TF1 لازم را ایجاد کنید.
# Create a TF1 SavedModel
SAVED_MODEL_DIR = "tf_saved_model/"
remove_dir(SAVED_MODEL_DIR)
with tf1.Graph().as_default() as g:
with tf1.Session() as sess:
input = tf1.placeholder(tf.float32, shape=(3,), name='input')
output = input + 2
# print("result: ", sess.run(output, {input: [0., 2., 4.]}))
tf1.saved_model.simple_save(
sess, SAVED_MODEL_DIR,
inputs={'input': input},
outputs={'output': output})
print("TF1 SavedModel path: ", SAVED_MODEL_DIR)
# Create a TF1 Keras model
KERAS_MODEL_PATH = 'tf_keras_model.h5'
model = tf1.keras.models.Sequential([
tf1.keras.layers.InputLayer(input_shape=(128, 128, 3,), name='input'),
tf1.keras.layers.Dense(units=16, input_shape=(128, 128, 3,), activation='relu'),
tf1.keras.layers.Dense(units=1, name='output')
])
model.save(KERAS_MODEL_PATH, save_format='h5')
print("TF1 Keras Model path: ", KERAS_MODEL_PATH)
# Create a TF1 frozen GraphDef model
GRAPH_DEF_MODEL_PATH = tf.keras.utils.get_file(
'mobilenet_v1_0.25_128',
origin='https://storage.googleapis.com/download.tensorflow.org/models/mobilenet_v1_0.25_128_frozen.tgz',
untar=True,
) + '/frozen_graph.pb'
print("TF1 frozen GraphDef path: ", GRAPH_DEF_MODEL_PATH)
TF1 SavedModel path: tf_saved_model/ TF1 Keras Model path: tf_keras_model.h5 Downloading data from https://storage.googleapis.com/download.tensorflow.org/models/mobilenet_v1_0.25_128_frozen.tgz 2621440/2617289 [==============================] - 0s 0us/step 2629632/2617289 [==============================] - 0s 0us/step TF1 frozen GraphDef path: /home/kbuilder/.keras/datasets/mobilenet_v1_0.25_128/frozen_graph.pb
1. یک TF1 SavedModel را به مدل TFLite تبدیل کنید
قبل: تبدیل با TF1
این کد معمولی برای تبدیل TFlite به سبک TF1 است.
converter = tf1.lite.TFLiteConverter.from_saved_model(
saved_model_dir=SAVED_MODEL_DIR,
input_arrays=['input'],
input_shapes={'input' : [3]}
)
converter.optimizations = {tf.lite.Optimize.DEFAULT}
converter.change_concat_input_ranges = True
tflite_model = converter.convert()
# Ignore warning: "Use '@tf.function' or '@defun' to decorate the function."
2021-09-22 20:02:56.143221: W tensorflow/compiler/mlir/lite/python/tf_tfl_flatbuffer_helpers.cc:351] Ignored output_format. 2021-09-22 20:02:56.143267: W tensorflow/compiler/mlir/lite/python/tf_tfl_flatbuffer_helpers.cc:354] Ignored drop_control_dependency. 2021-09-22 20:02:56.143274: W tensorflow/compiler/mlir/lite/python/tf_tfl_flatbuffer_helpers.cc:360] Ignored change_concat_input_ranges.
بعد: تبدیل با TF2
مستقیماً TF1 SavedModel را به یک مدل TFLite تبدیل کنید، با یک پرچم مبدل v2 کوچکتر.
# Convert TF1 SavedModel to a TFLite model.
converter = tf.lite.TFLiteConverter.from_saved_model(saved_model_dir=SAVED_MODEL_DIR)
converter.optimizations = {tf.lite.Optimize.DEFAULT}
tflite_model = converter.convert()
2021-09-22 20:02:56.207882: W tensorflow/compiler/mlir/lite/python/tf_tfl_flatbuffer_helpers.cc:351] Ignored output_format. 2021-09-22 20:02:56.207923: W tensorflow/compiler/mlir/lite/python/tf_tfl_flatbuffer_helpers.cc:354] Ignored drop_control_dependency. 2021-09-22 20:02:56.207930: W tensorflow/compiler/mlir/lite/python/tf_tfl_flatbuffer_helpers.cc:360] Ignored change_concat_input_ranges.
2. یک فایل مدل TF1 Keras را به مدل TFLite تبدیل کنید
قبل: تبدیل با TF1
این کد معمولی برای تبدیل TFlite به سبک TF1 است.
converter = tf1.lite.TFLiteConverter.from_keras_model_file(model_file=KERAS_MODEL_PATH)
converter.optimizations = {tf.lite.Optimize.DEFAULT}
converter.change_concat_input_ranges = True
tflite_model = converter.convert()
2021-09-22 20:02:56.608343: W tensorflow/python/util/util.cc:348] Sets are not currently considered sequences, but this may change in the future, so consider avoiding using them. 2021-09-22 20:02:57.119836: W tensorflow/compiler/mlir/lite/python/tf_tfl_flatbuffer_helpers.cc:351] Ignored output_format. 2021-09-22 20:02:57.119881: W tensorflow/compiler/mlir/lite/python/tf_tfl_flatbuffer_helpers.cc:354] Ignored drop_control_dependency. 2021-09-22 20:02:57.119888: W tensorflow/compiler/mlir/lite/python/tf_tfl_flatbuffer_helpers.cc:360] Ignored change_concat_input_ranges.
بعد: تبدیل با TF2
ابتدا فایل مدل TF1 Keras را به TF2 SavedModel تبدیل کنید و سپس آن را به مدل TFLite تبدیل کنید، با مجموعه پرچم های مبدل v2 کوچکتر.
# Convert TF1 Keras model file to TF2 SavedModel.
model = tf.keras.models.load_model(KERAS_MODEL_PATH)
model.save(filepath='saved_model_2/')
# Convert TF2 SavedModel to a TFLite model.
converter = tf.lite.TFLiteConverter.from_saved_model(saved_model_dir='saved_model_2/')
tflite_model = converter.convert()
2021-09-22 20:02:57.943564: W tensorflow/compiler/mlir/lite/python/tf_tfl_flatbuffer_helpers.cc:351] Ignored output_format. 2021-09-22 20:02:57.943608: W tensorflow/compiler/mlir/lite/python/tf_tfl_flatbuffer_helpers.cc:354] Ignored drop_control_dependency. 2021-09-22 20:02:57.943614: W tensorflow/compiler/mlir/lite/python/tf_tfl_flatbuffer_helpers.cc:360] Ignored change_concat_input_ranges.
3. یک GraphDef منجمد TF1 را به مدل TFLite تبدیل کنید
قبل: تبدیل با TF1
این کد معمولی برای تبدیل TFlite به سبک TF1 است.
converter = tf1.lite.TFLiteConverter.from_frozen_graph(
graph_def_file=GRAPH_DEF_MODEL_PATH,
input_arrays=['input'],
input_shapes={'input' : [1, 128, 128, 3]},
output_arrays=['MobilenetV1/Predictions/Softmax'],
)
converter.optimizations = {tf.lite.Optimize.DEFAULT}
converter.change_concat_input_ranges = True
tflite_model = converter.convert()
2021-09-22 20:02:58.139650: W tensorflow/compiler/mlir/lite/python/tf_tfl_flatbuffer_helpers.cc:351] Ignored output_format. 2021-09-22 20:02:58.139707: W tensorflow/compiler/mlir/lite/python/tf_tfl_flatbuffer_helpers.cc:354] Ignored drop_control_dependency. 2021-09-22 20:02:58.139721: W tensorflow/compiler/mlir/lite/python/tf_tfl_flatbuffer_helpers.cc:360] Ignored change_concat_input_ranges.
بعد: تبدیل با TF2
ابتدا GraphDef منجمد TF1 را به TF1 SavedModel تبدیل کنید و سپس آن را به مدل TFLite تبدیل کنید، با یک پرچم مبدل v2 کوچکتر.
## Convert TF1 frozen Graph to TF1 SavedModel.
# Load the graph as a v1.GraphDef
import pathlib
gdef = tf.compat.v1.GraphDef()
gdef.ParseFromString(pathlib.Path(GRAPH_DEF_MODEL_PATH).read_bytes())
# Convert the GraphDef to a tf.Graph
with tf.Graph().as_default() as g:
tf.graph_util.import_graph_def(gdef, name="")
# Lookup the input and output tensors.
input_tensor = g.get_tensor_by_name('input:0')
output_tensor = g.get_tensor_by_name('MobilenetV1/Predictions/Softmax:0')
# Save the graph as a TF1 Savedmodel
remove_dir('saved_model_3/')
with tf.compat.v1.Session(graph=g) as s:
tf.compat.v1.saved_model.simple_save(
session=s,
export_dir='saved_model_3/',
inputs={'input':input_tensor},
outputs={'output':output_tensor})
# Convert TF1 SavedModel to a TFLite model.
converter = tf.lite.TFLiteConverter.from_saved_model(saved_model_dir='saved_model_3/')
converter.optimizations = {tf.lite.Optimize.DEFAULT}
tflite_model = converter.convert()
2021-09-22 20:02:58.874490: W tensorflow/compiler/mlir/lite/python/tf_tfl_flatbuffer_helpers.cc:351] Ignored output_format. 2021-09-22 20:02:58.874538: W tensorflow/compiler/mlir/lite/python/tf_tfl_flatbuffer_helpers.cc:354] Ignored drop_control_dependency. 2021-09-22 20:02:58.874545: W tensorflow/compiler/mlir/lite/python/tf_tfl_flatbuffer_helpers.cc:360] Ignored change_concat_input_ranges.
خواندن بیشتر
- برای اطلاعات بیشتر در مورد گردش کار و آخرین ویژگی ها به راهنمای TFLite مراجعه کنید.
- اگر از کد TF1 یا قالبهای مدل قدیمی TF1 استفاده میکنید (فایلهای Keras
.h5، GraphDef ثابت.pbو غیره)، لطفاً کد خود را بهروزرسانی کنید و مدلهای خود را به قالب TF2 SavedModel منتقل کنید.
مشاهده در TensorFlow.org
در Google Colab اجرا شود
مشاهده منبع در GitHub
دانلود دفترچه یادداشت