Chuyển đổi mô hình TensorFlow

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ơ đồ bên dưới minh họa quy trình làm việc cấp cao để chuyển đổi mô hình của bạn:

Quy trình chuyển đổi TFLite

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:

  1. 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.
  2. Dòng lệnh : Điều này chỉ hỗ trợ chuyển đổi mô hình cơ bản.

API Python

Mã 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 cách sử dụng tf.lite.TFLiteConverter . Mô hình TensorFlow được lưu trữ bằng định dạng SavingModel 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ụ nằm trong một số phần tiếp theo):

Ví dụ sau đây cho thấy cách chuyển đổi SavingModel 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 hàm cụ thể

Ví dụ sau đây cho thấy cách chuyển đổi các hàm 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 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 hơn nữa độ trễ và kích thước mô hình của bạn với độ chính xác bị mất ở mứ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 khắc phục:

  • 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ó các hoạt động TF không 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 chỉ muốn tạo một mô hình với các hoạt động TFLite, bạn có thể thêm yêu cầu cho hoạt động TFLite bị thiếu trong Github issue #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 TFLite op .

  • Lỗi: .. is neither a custom op nor a flex op

    Giải pháp: Nếu hoạt động TF này là:

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 đã 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 SavingModel

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, thiết bị nhúng).