Trang này mô tả cách chuyển đổi mô hình TensorFlow sang mô hình TensorFlow Lite (định dạng FlatBuffer được tối ưu hóa được xác định bởi phần mở rộng tệp .tflite
) bằng trình chuyển đổi TensorFlow Lite.
Quy trình chuyển đổi
Sơ đồ dưới đây minh họa quy trình làm việc cấp cao để chuyển đổi mô hình của bạn:
Hình 1. Quy trình làm việc của bộ chuyển đổi.
Bạn có thể chuyển đổi mô hình của mình bằng một trong các tùy chọn sau:
- API Python ( được khuyến nghị ): Điều này cho phép bạn tích hợp chuyển đổi vào quy trình phát triển của mình, áp dụng tối ưu hóa, thêm siêu dữ liệu và nhiều tác vụ khác giúp đơn giản hóa quá trình chuyển đổi.
- Dòng lệnh : Điều này chỉ hỗ trợ chuyển đổi mô hình cơ bản.
API Python
Mã trình trợ giúp: Để tìm hiểu thêm về API trình chuyển đổi TensorFlow Lite, hãy chạy print(help(tf.lite.TFLiteConverter))
.
Chuyển đổi mô hình TensorFlow bằng tf.lite.TFLiteConverter
. Mô hình TensorFlow được lưu trữ bằng định dạng SavedModel và được tạo bằng cách sử dụng API tf.keras.*
Cấp cao (mô hình Keras) hoặc API tf.*
Cấp thấp (từ đó bạn tạo các hàm 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()
( được khuyến nghị ): Chuyển đổi Mô hình đã lưu . -
tf.lite.TFLiteConverter.from_keras_model()
: Chuyển đổi mô hình Keras . -
tf.lite.TFLiteConverter.from_concrete_functions()
: Chuyển đổi các hàm cụ thể .
Chuyển đổi SavedModel (được khuyến nghị)
Ví dụ sau đây cho thấy cách chuyển đổi SavedModel thành 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
Ví dụ sau đây cho thấy cách chuyển đổi mô hình Keras thành 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ể
Ví dụ sau đây cho thấy cách chuyển đổi các chức năng cụ thể thành 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.
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 cách tối ưu hóa phổ biến được sử dụng là lượng tử hóa sau đào tạo , điều này có thể làm giảm thêm độ trễ và kích thước mô hình của bạn với độ chính xác tối thiểu.
Thêm siêu dữ liệu , giúp tạo mã trình bao bọc dành riêng cho nền tảng dễ dàng hơn khi triển khai mô hình trên 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 vấn đề này bằng cách sử dụng TF op trong mô hình TFLite (được khuyến nghị). Nếu bạn muốn tạo một mô hình chỉ có hoạt động TFLite, bạn có thể thêm yêu cầu cho tùy chọn TFLite bị thiếu trong vấn đề Github # 21526 (để lại nhận xét nếu yêu cầu của bạn chưa được đề cập) hoặc tự tạo tùy chọn TFLite .
Lỗi:
.. is neither a custom op nor a flex op
Giải pháp: Nếu TF op này là:
Được hỗ trợ trong TF: Lỗi xảy ra do TF op bị thiếu trong danh sách cho phép (danh sách đầy đủ các hoạt động TF được 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 TF op .
- Chuyển đổi mô hình TF sang mô hình TFLite .
- Tạo op TFLite và chạy suy luận bằng cách liên kết nó với thời gian chạy TFLite.
Công cụ dòng lệnh
Nếu bạn đã cài đặt TensorFlow 2.x từ pip , hãy sử dụng lệnh tflite_convert
. Để xem tất cả các cờ có sẵn, hãy 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.
Nếu bạn chưa tải nguồn TensorFlow 2.x và muốn chạy trình chuyển đổi từ nguồn đó mà không cần xây dựng và cài đặt gói, bạn có thể thay thế ' tflite_convert
' bằng ' bazel run tensorflow/lite/python:tflite_convert --
' trong lệnh.
Chuyển đổi một SavedModel
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 trình thông dịch TensorFlow Lite để chạy suy luận trên thiết bị khách (ví dụ: thiết bị di động, được nhúng).