Section 4/161 menit

4. Setup: Menambahkan Model ke Project

4. Setup: Menambahkan Model ke Project

Opsi A: Download Model dari Apple (Paling Mudah)

Apple menyediakan berbagai pre-trained model di situs developer:

  1. Buka developer.apple.com/machine-learning/models
  2. Download model yang diinginkan (contoh: MobileNetV2.mlmodel)
  3. Drag file .mlmodel ke navigator Xcode
  4. Pastikan "Add to targets" dicentang untuk target yang tepat
  5. Xcode otomatis generate Swift class dengan nama yang sama

Opsi B: Convert Model dari PyTorch/TensorFlow

swift
# Script Python untuk konversi (dijalankan di Mac, bukan di iOS)
import coremltools as ct
import torch

# Load PyTorch model
pytorch_model = MyPyTorchModel()
pytorch_model.eval()

# Trace model
example_input = torch.rand(1, 3, 224, 224)
traced_model = torch.jit.trace(pytorch_model, example_input)

# Convert ke Core ML
mlmodel = ct.convert(
    traced_model,
    inputs=[ct.ImageType(
        name="image",
        shape=(1, 3, 224, 224),
        bias=[-0.485/0.229, -0.456/0.224, -0.406/0.225],
        scale=1/(255.0 * 0.229)
    )],
    outputs=[ct.ClassifierConfig(class_labels="labels.txt")],
    minimum_deployment_target=ct.target.iOS15,
)

# Tambahkan metadata
mlmodel.short_description = "Custom image classifier"
mlmodel.author = "My Team"
mlmodel.version = "1.0"

# Save
mlmodel.save("MyClassifier.mlpackage")

Opsi C: Buat Model dengan Create ML (Tanpa Code)

Create ML adalah aplikasi macOS (bawaan Xcode) untuk melatih model tanpa Python:

  1. Buka Xcode → Open Developer Tool → Create ML
  2. Pilih template: Image Classification, Object Detection, Text Classification, dll
  3. Drag training data ke Create ML
  4. Klik Train — model dilatih langsung di Mac menggunakan GPU/Neural Engine
  5. Export sebagai .mlpackage

Struktur Project Setelah Menambahkan Model

swift
MyApp/
├── MyApp.xcodeproj
├── MyApp/
│   ├── Models/
│   │   ├── ImageClassifier.mlpackage      ← source model
│   │   └── SentimentAnalyzer.mlpackage    ← source model
│   ├── Services/
│   │   └── MLService.swift
│   └── ...
└── MyApp.xcarchive/
    └── Products/Applications/MyApp.app/
        └── ImageClassifier.mlmodelc       ← compiled model (auto)

Melihat Informasi Model di Xcode

Klik file .mlmodel di navigator → Xcode tampilkan:

  • Inputs: nama, tipe, shape
  • Outputs: nama, tipe, shape
  • Metadata: author, license, versi
  • Preview: test model langsung dari Xcode (untuk beberapa tipe model)
  • Utilities: ukuran model, estimasi performa