3
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 3 years have passed since last update.

Unity備忘録 .h5形式から.onnx形式への変更に七転八倒した話

Last updated at Posted at 2022-03-26

UnityのBarracudaにAIモデルを適用するためには、
作成したAIのモデル(.h5)形式を.onnx形式に変換する必要がありました。

変換の方法ですが、keras2onnxを試してもエラーで全く動作しなかったため、
tf2onnxを使ってモデル変換に成功しました。

重大事項としてtf2onnxは.h5形式に非対応のため、
そもそもモデル作成時に.h5形式で保存するのではなく、
TensorFlow SavedModel形式でフォルダごと書き出す対応が必要になります。

つまりモデル作成時に

save_model_path = os.path.join(backup_dir, 'my_model.h5')
model.save(save_model_path)

ではなく、

save_model_path = os.path.join(backup_dir, 'my_model')
model.save(save_model_path)

という.h5拡張子を付けないコードで保存すると、
TensorFlow SavedModel形式として、モデルがフォルダごと生成されます。

その後、Macのターミナル上で下記のコマンドを実行することで、
文末のmy_model.onnxという変換後のモデルが生成されます。

python3 -m tf2onnx.convert --saved-model my_model --output my_model.onnx

ちなみにtf2onnxを使用するためには、
あらかじめいくつかインポートしておく必要がありますので、
下記を参考にしてくださいね。
https://github.com/onnx/tensorflow-onnx

3
0
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
3
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?