Các TensorFlow Lite Chuyển đổi lấy một mô hình TensorFlow và tạo ra một mô hình TensorFlow Lite (một tối ưu hóa FlatBuffer định dạng xác định bởi các .tflite
phần mở rộng tập tin). Bạn có hai tùy chọn sau để sử dụng trình chuyển đổi:
- Python API (đề nghị): Điều này làm cho nó dễ dàng hơn để chuyển đổi mô hình như là một phần của đường ống phát triển mô hình, áp dụng tối ưu hóa, thêm siêu dữ liệu và có nhiều tính năng hơn.
- Dòng lệnh : Đây chỉ hỗ trợ chuyển đổi mô hình cơ bản.
API Python
Mã giúp đỡ: Để xác định các phiên bản cài đặt TensorFlow, chạy print(tf.__version__)
và tìm hiểu thêm về công cụ chuyển đổi API TensorFlow Lite, chạy print(help(tf.lite.TFLiteConverter))
.
Nếu bạn đã cài đặt TensorFlow 2.x , bạn có hai tùy chọn sau: (nếu bạn đã cài đặt TensorFlow 1.x , hãy tham khảo Github )
Chuyển đổi mô hình TensorFlow 2.x sử dụng
tf.lite.TFLiteConverter
. Một TensorFlow mô hình 2.x được lưu trữ bằng cách sử dụng định dạng SavedModel và được tạo ra hoặc sử dụng cấp caotf.keras.*
API (một mô hình Keras) hoặc ở mức độ thấptf.*
API (từ mà bạn tạo ra các chức năng cụ thể). Kết quả là bạn có ba tùy chọn sau (ví dụ trong một vài phần tiếp theo):-
tf.lite.TFLiteConverter.from_saved_model()
(đề nghị): Chuyển đổi một SavedModel . -
tf.lite.TFLiteConverter.from_keras_model()
: Chuyển đổi một Keras mô hình. -
tf.lite.TFLiteConverter.from_concrete_functions()
: Chuyển đổi chức năng cụ thể .
-
Chuyển đổi mô hình TensorFlow 1.x sử dụng
tf.compat.v1.lite.TFLiteConverter
(ví dụ là trên Github ):-
tf.compat.v1.lite.TFLiteConverter.from_saved_model()
: Chuyển đổi một SavedModel . -
tf.compat.v1.lite.TFLiteConverter.from_keras_model_file()
: Chuyển đổi một Keras mô hình. -
tf.compat.v1.lite.TFLiteConverter.from_session()
: Chuyển đổi một GraphDef từ một phiên làm việc. -
tf.compat.v1.lite.TFLiteConverter.from_frozen_graph()
: Chuyển đổi một Frozen GraphDef từ một tập tin. Nếu bạn có các điểm kiểm tra, sau đó đầu tiên chuyển đổi nó vào một tập tin Frozen GraphDef và sau đó sử dụng API này như thể hiện ở đây .
-
Chuyển đổi SavedModel (được khuyến nghị)
Các chương trình ví dụ sau đây làm thế nào để chuyển đổi một SavedModel vào một mô hình 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)
Chuyển đổi mô hình Keras
Các chương trình ví dụ sau đây làm thế nào để chuyển đổi một Keras mô hình thành một mô hình 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)
Chuyển đổi các chức năng cụ thể
Các chương trình ví dụ sau đây làm thế nào để chuyển đổi chức năng cụ thể vào một mô hình 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.
# 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)
Các tính năng khác
Áp dụng tối ưu hóa . Một tối ưu hóa thường được sử dụng là bài huấn luyện lượng tử , mà hơn nữa có thể giảm độ trễ mô hình của bạn và kích thước với sự mất mát tối thiểu trong độ chính xác.
Thêm siêu dữ liệu , mà làm cho nó dễ dàng hơn để tạo mã wrapper nền tảng cụ thể khi triển khai mô hình trên các thiết bị.
Lỗi chuyển đổi
Sau đây là các lỗi chuyển đổi phổ biến và giải pháp của chúng:
Lỗi:
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: ..., .., ...
Giải pháp: Lỗi xảy ra do mô hình của bạn có TF hoạt động không có triển khai TFLite tương ứng. Bạn có thể giải quyết điều này bằng cách sử dụng op TF trong mô hình TFLite (recommended). Nếu bạn muốn tạo ra một mô hình với TFLite chỉ ops, bạn có thể thêm một yêu cầu cho thiếu TFLite op trong Github vấn đề # 21.526 (để lại nhận xét nếu yêu cầu của bạn đã không được đề cập) hoặc tạo ra các op TFLite mình.
Lỗi:
.. is neither a custom op nor a flex op
Giải pháp: Nếu TF op này là:
Hỗ trợ trong TF: Lỗi này xảy ra bởi vì TF op là mất tích từ allowlist (một danh sách đầy đủ các ops TF hỗ trợ bởi TFLite). Bạn có thể giải quyết vấn đề này như sau:
Không được hỗ trợ trong TF: Lỗi xảy ra do TFLite không biết về toán tử TF tùy chỉnh do bạn xác định. Bạn có thể giải quyết vấn đề này như sau:
- Tạo op TF .
- Chuyển đổi mô hình TF đến một mô hình TFLite .
- Tạo op TFLite và chạy suy luận bằng cách liên kết nó vào thời gian chạy TFLite.
Công cụ dòng lệnh
Nó là rất khuyến khích bạn nên sử dụng API Python liệt kê ở trên thay vào đó, nếu có thể.
Nếu bạn đã cài đặt TensorFlow 2.x từ pip , sử dụng tflite_convert
lệnh như sau: (nếu bạn đã cài đặt TensorFlow 2.x từ nguồn sau đó bạn có thể thay thế ' tflite_convert
' với ' bazel run //tensorflow/lite/python:tflite_convert --
'trong các phần sau, và nếu bạn đã cài đặt TensorFlow 1.x sau đó tham khảo Github ( tài liệu tham khảo , ví dụ ))
tflite_convert
: Để xem tất cả các lá cờ có sẵn, sử dụng lệnh sau:
$ 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.
Chuyển đổi Mô hình đã Lưu
tflite_convert \
--saved_model_dir=/tmp/mobilenet_saved_model \
--output_file=/tmp/mobilenet.tflite
Chuyển đổi mô hình Keras H5
tflite_convert \
--keras_model_file=/tmp/mobilenet_keras_model.h5 \
--output_file=/tmp/mobilenet.tflite
Bước tiếp theo
Sử dụng thông dịch viên TensorFlow Lite để chạy suy luận trên một thiết bị client (ví dụ điện thoại di động, nhúng).