Section 2/161 menit

2. Masalah yang Dipecahkan

2. Masalah yang Dipecahkan

Inferensi di Server: Latensi dan Privasi

swift
// ❌ TANPA Core ML: inferensi via REST API — latensi, privasi, dan offline dependency
func classifyImageViaAPI(image: UIImage) async throws -> String {
    let imageData = image.jpegData(compressionQuality: 0.8)!
    var request = URLRequest(url: URL(string: "https://api.example.com/classify")!)
    request.httpMethod = "POST"
    request.httpBody = imageData
    
    let (data, _) = try await URLSession.shared.data(for: request)
    let result = try JSONDecoder().decode(ClassificationResult.self, from: data)
    
    // Masalah 1: Butuh koneksi internet
    // Masalah 2: Data gambar dikirim ke server — privasi
    // Masalah 3: Latensi network 100ms–2000ms
    // Masalah 4: Biaya API per request
    return result.label
}
swift
// ✓ DENGAN Core ML: inferensi on-device — <10ms, offline, private
func classifyImageOnDevice(image: UIImage) throws -> String {
    let model = try MobileNetV2(configuration: MLModelConfiguration())
    let input = try MobileNetV2Input(imageWith: image.cgImage!)
    let output = try model.prediction(input: input)
    
    // Keuntungan:
    // ✓ Bekerja offline
    // ✓ Data tidak meninggalkan device
    // ✓ Latensi <10ms di Neural Engine
    // ✓ Tidak ada biaya API
    return output.classLabel
}

Integrasi Model Tanpa Boilerplate

swift
// ❌ TANPA Code Generation: manual setup tensor input/output
func predictManually(pixelBuffer: CVPixelBuffer) throws -> [String: Double] {
    let modelURL = Bundle.main.url(forResource: "MyModel", withExtension: "mlmodelc")!
    let model = try MLModel(contentsOf: modelURL)
    
    let inputFeatures: [String: Any] = ["image": pixelBuffer]
    let provider = try MLDictionaryFeatureProvider(dictionary: inputFeatures)
    let output = try model.prediction(from: provider)
    
    // Cast manual yang error-prone
    guard let probs = output.featureValue(for: "classLabelProbs")?.dictionaryValue else {
        throw PredictionError.invalidOutput
    }
    return probs as! [String: Double]
}
swift
// ✓ DENGAN Core ML Code Generation: Xcode generate type-safe Swift class otomatis
// Cukup drag .mlmodel ke Xcode → Xcode generate MyModel.swift secara otomatis
func predictTypeSafe(pixelBuffer: CVPixelBuffer) throws -> MyModelOutput {
    let model = try MyModel()
    let input = MyModelInput(image: pixelBuffer)
    return try model.prediction(input: input)
    // output.classLabel → String (type-safe, auto-complete)
    // output.classLabelProbs → [String: Double] (type-safe)
}