0
2

More than 3 years have passed since last update.

Google Colabを用いてPytorchのモデルをTFLiteに変換

Posted at

何の記事?

PytorchのモデルからTensorflow Liteへの変換を、Google colabを用いて行う方法です。

Pytorch → ONNX

import torch
import torchvision.models as models

model_name = "resnet50"

dummy_input = torch.randn((1, 3, 224, 224))
model = models.resnet50()
torch.onnx.export(model, dummy_input, "converted.onnx", verbose=True, input_names=['input'], output_names=['output'])

ONNX → Tensorflow

!pip install onnx_tf
from onnx_tf.backend import prepare
import onnx

TF_PATH = "./converted.pb" 
ONNX_PATH = "./converted.onnx" 
onnx_model = onnx.load(ONNX_PATH)  


tf_rep = prepare(onnx_model)  
tf_rep.export_graph(TF_PATH)

Tensorflow → TFLite

# Convert the model
converter = tf.lite.TFLiteConverter.from_saved_model(TF_PATH) # path to the SavedModel directory
converter.target_spec.supported_ops = [
  tf.lite.OpsSet.TFLITE_BUILTINS, # enable TensorFlow Lite ops.
  tf.lite.OpsSet.SELECT_TF_OPS # enable TensorFlow ops.
]
tflite_model = converter.convert()

# Save the model.
with open(model_name +".tflite", "wb") as f:
  f.write(tflite_model)

最後に

細かい説明は省略します。コピペでOKです。

0
2
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
0
2