如何将 Tensorflow.js (.json) 模型转换为 Tensorflow (SavedModel) 或 Tensorflow Lite (.tflite) 模型?

How to convert from Tensorflow.js (.json) model into Tensorflow (SavedModel) or Tensorflow Lite (.tflite) model?

我有 downloaded Google Tensorflow.js (tfjs) 的预训练 PoseNet 模型,所以它是 json 文件.

但是,我想在Android上使用它,所以我需要.tflite模型。虽然有人 'ported' 从 tfjs 到 tflite here 的类似模型,但我不知道他们转换的是什么模型(PoseNet 有很多变体)。我想自己做这些步骤。此外,我不想 运行 一些任意代码上传到 Whosebug 中的文件中:

Caution: Be careful with untrusted code—TensorFlow models are code. See Using TensorFlow Securely for details. Tensorflow docs

有谁知道有什么方便的方法吗?

您可以通过查看 json 文件来了解您拥有的 tfjs 格式。它经常说“图形模型”。它们之间的区别是.

从 tfjs 图模型到 SavedModel(更常见)

使用tfjs-to-tf by Patrick Levin.

import tfjs_graph_converter.api as tfjs
tfjs.graph_model_to_saved_model(
               "savedmodel/posenet/mobilenet/float/050/model-stride16.json",
               "realsavedmodel"
            )

# Code below taken from https://www.tensorflow.org/lite/convert/python_api
converter = tf.lite.TFLiteConverter.from_saved_model("realsavedmodel")
tflite_model = converter.convert()

# Save the TF Lite model.
with tf.io.gfile.GFile('model.tflite', 'wb') as f:
  f.write(tflite_model)

从 tfjs 层模型到 SavedModel

注意:这仅适用于图层模型格式,不适用于问题中的图形模型格式。它们的区别我写了.


  1. Install and use tensorflowjs-convert to convert the .json file into a Keras HDF5 file (from another SO thread).

在 mac,您将遇到问题 运行ning pyenv (fix) and on Z-shell, pyenv won't load correctly (fix)。此外,一旦 pyenv 是 运行ning,请使用 python -m pip install tensorflowjs 而不是 pip install tensorflowjs,因为 pyenv 没有更改 pip 对我使用的 python。

一旦您按照 tensorflowjs_converter guide、运行 tensorflowjs_converter 验证其正常工作,并且应该就 Missing input_path argument 向您发出警告。那么:

tensorflowjs_converter --input_format=tfjs_layers_model --output_format=keras tfjs_model.json hdf5_keras_model.hdf5
  1. 将 Keras HDF5 文件转换为 SavedModel(标准 Tensorflow 模型文件)或使用 TFLiteConverter 直接转换为 .tflite 文件。 Python 文件中的以下 运行s:
# Convert the model.
model = tf.keras.models.load_model('hdf5_keras_model.hdf5')
converter = tf.lite.TFLiteConverter.from_keras_model(model)
tflite_model = converter.convert() 
    
# Save the TF Lite model.
with tf.io.gfile.GFile('model.tflite', 'wb') as f:
f.write(tflite_model)

或保存到 SavedModel:

# Convert the model.
model = tf.keras.models.load_model('hdf5_keras_model.hdf5')
tf.keras.models.save_model(
    model, filepath, overwrite=True, include_optimizer=True, save_format=None,
    signatures=None, options=None
)