0
0

Pytoch(.pt)をCoreMLに変換する

Posted at

Pytoch(.pt)をCoreMLに変換する

CoreMLでは事前に学習させていたモデルをCoreMLモデルに簡単に変換できます

1.同じ階層に.ptファイルを用意する

2.以下のコードを実行するだけ

coreml.py
from ultralytics import YOLO#インポート

model = YOLO('./best.pt') 
model.export(format='coreml', nms=True)

この変換方法はUltralytics YOLOの方法を用いています。

他にも、CoreMLToolsを使用する方法

import coremltools as ct
import torch
import torchvision

# PyTorchモデルの定義とロード
model = torchvision.models.resnet18(pretrained=True)
model.eval()

# サンプル入力の作成
example_input = torch.rand(1, 3, 224, 224)

# トレースモデルの作成
traced_model = torch.jit.trace(model, example_input)

# CoreMLモデルに変換
coreml_model = ct.convert(traced_model, inputs=[ct.TensorType(name="input", shape=example_input.shape)])

# CoreMLモデルの保存
coreml_model.save("ResNet18.mlmodel")

など変換方法は様々です。

どちらの方法を選ぶかは、使用しているモデルやプロジェクトの要件に依存します。YOLOモデルの場合はUltralyticsの方法が簡便で便利ですし、他のフレームワークからの変換や細かいカスタマイズが必要な場合はCoreMLToolsを使用することが一般的です。
0
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
0
0