Tüm Yazılar
KategoriAI & ML
Okuma Süresi
24 dk okuma
Yayın Tarihi
...
Kelime Sayısı
1.403kelime

Kahveni hazırla - bu içerikli bir makale!

On-device ML ile gizlilik odaklı, hızlı ve offline çalışan iOS uygulamaları geliştirme. Core ML, Neural Engine ve model optimizasyonu.

iOS On-Device Machine Learning Rehberi

# iOS On-Device Machine Learning Rehberi

Mobil cihazlarda makine ogrenmesi artik bir luks degil, zorunluluk haline geldi. Apple'in Neural Engine'i, A-serisi ve M-serisi ciplerle birlikte iOS cihazlarini birer AI makinesine donusturdu. Bu rehberde on-device ML'in tum inceliklerini, Core ML entegrasyonunu ve production-ready model deploy stratejilerini ogreneceksin.

"Kullanicinin verisini sunucuya gondermeden, cihaz uzerinde isleyebilmek hem gizlilik hem de performans acisindan devrim niteliginde." — Apple ML Team, WWDC23

Icindekiler


1. On-Device ML Nedir?

On-device ML, makine ogrenmesi modellerinin tamamen kullanicinin cihazinda calismasini ifade eder. Sunucu bagimliligini ortadan kaldirir ve birden fazla avantaj sunar.

Server-Side vs On-Device Karsilastirmasi

Ozellik
Server-Side ML
On-Device ML
Latency
100-500ms (network)
1-10ms
Gizlilik
Veri sunucuya gider
Veri cihazda kalir
Offline
Calismaz
Calisir
Maliyet
Sunucu maliyeti var
Ucretsiz inference
Model Boyutu
Sinir yok
Cihaz limiti
Guncelleme
Aninda
App update gerekli
Compute
GPU cluster
Neural Engine/GPU

On-device ML secerken su kriterlere bak: Modelin 200MB'dan kucuk mu? Latency kritik mi? Kullanici verisinin gizliligi onemli mi? Offline calisma gerekli mi? Bunlarin coguna evet diyorsan, on-device ML dogru secim.


2. Apple Neural Engine Mimarisi

Apple Neural Engine (ANE), ozellikle ML inference icin tasarlanmis bir donanim bilesenidir. iPhone 8 Plus ve sonrasinda (A11+) mevcuttur.

Neural Engine Nesilleri

Cip
Neural Engine
TOPS
Cekirdek
A11
1. nesil
0.6
2
A12
2. nesil
5
8
A14
3. nesil
11
16
A15
4. nesil
15.8
16
A16
5. nesil
17
16
A17 Pro
6. nesil
35
16
M1
-
11
16
M2
-
15.8
16
M4
-
38
16
TOPS = Trillion Operations Per Second (Saniyede trilyon islem)

ANE, ozellikle convolution ve matrix multiplication islemleri icin optimize edilmistir. Ayni islemi CPU'ya gore 10-15 kat daha hizli ve cok daha az enerji harcayarak gerceklestirir.


3. Core ML Framework Temelleri

Core ML, Apple'in on-device ML framework'udur ve tum ML islemlerini soyutlar.

swift
1import CoreML
2 
3// Core ML model yukleme ve tahmin
4class MLPredictor {
5 private var model: MLModel?
6 
7 init() {
8 // Model yukleme - lazy initialization
9 do {
10 let config = MLModelConfiguration()
11 config.computeUnits = .all // CPU + GPU + Neural Engine
12 self.model = try ImageClassifier(configuration: config).model
13 } catch {
14 print("Model yuklenemedi: \(error.localizedDescription)")
15 }
16 }
17 
18 func predict(image: CVPixelBuffer) async throws -> String {
19 guard let model = model else {
20 throw MLError.modelNotLoaded
21 }
22 
23 let input = try MLDictionaryFeatureProvider(
24 dictionary: ["image": MLFeatureValue(pixelBuffer: image)]
25 )
26 
27 let output = try await model.prediction(from: input)
28 
29 guard let result = output.featureValue(for: "classLabel")?.stringValue else {
30 throw MLError.predictionFailed
31 }
32 
33 return result
34 }
35}
36 
37enum MLError: Error {
38 case modelNotLoaded
39 case predictionFailed
40}

Compute Units Secimi

Core ML uc farkli compute unit destekler:

swift
1let config = MLModelConfiguration()
2 
3// Sadece CPU - en yavas, en uyumlu
4config.computeUnits = .cpuOnly
5 
6// CPU + GPU - iyi performans
7config.computeUnits = .cpuAndGPU
8 
9// CPU + GPU + Neural Engine - en hizli (varsayilan)
10config.computeUnits = .all

.all secenegini kullandiginizda Core ML, her katmani en uygun donanim bileseninde calistirir. Ornegin convolution katmanlari Neural Engine'de, custom layer'lar CPU'da calisabilir.


4. Model Formatlari ve Donusumleri

Core ML, .mlmodel ve .mlpackage formatlarini destekler. Diger framework'lerden donusum icin coremltools kullanilir.

swift
1// Swift'te model bilgilerini okuma
2import CoreML
3 
4func inspectModel() throws {
5 let modelURL = Bundle.main.url(forResource: "MyModel", withExtension: "mlmodelc")!
6 let model = try MLModel(contentsOf: modelURL)
7 
8 let description = model.modelDescription
9 
10 // Input bilgileri
11 for (name, feature) in description.inputDescriptionsByName {
12 print("Input: \(name), Type: \(feature.type.rawValue)")
13 }
14 
15 // Output bilgileri
16 for (name, feature) in description.outputDescriptionsByName {
17 print("Output: \(name), Type: \(feature.type.rawValue)")
18 }
19 
20 // Metadata
21 if let metadata = description.metadata[.description] as? String {
22 print("Aciklama: \(metadata)")
23 }
24}

Donusum Araclari

Kaynak
Arac
Komut
PyTorch
coremltools
ct.convert(traced_model)
TensorFlow
coremltools
ct.convert(tf_model)
ONNX
coremltools
ct.converters.onnx.convert()
Keras
coremltools
ct.convert(keras_model)
scikit-learn
coremltools
ct.converters.sklearn.convert()

5. MLModel SwiftUI Entegrasyonu

swift
1import SwiftUI
2import CoreML
3import Vision
4 
5struct ImageClassifierView: View {
6 @State private var classificationResult = "Henuz siniflandirilmadi"
7 @State private var confidence: Double = 0.0
8 @State private var selectedImage: UIImage?
9 @State private var isProcessing = false
10 
11 var body: some View {
12 VStack(spacing: 20) {
13 if let image = selectedImage {
14 Image(uiImage: image)
15 .resizable()
16 .scaledToFit()
17 .frame(height: 300)
18 .cornerRadius(12)
19 }
20 
21 if isProcessing {
22 ProgressView("Analiz ediliyor...")
23 } else {
24 Text(classificationResult)
25 .font(.title2)
26 .fontWeight(.bold)
27 
28 if confidence > 0 {
29 Text("Guven: %\(Int(confidence * 100))")
30 .foregroundColor(.secondary)
31 }
32 }
33 
34 Button("Fotograf Sec") {
35 // PhotoPicker acilir
36 }
37 .buttonStyle(.borderedProminent)
38 }
39 .padding()
40 }
41 
42 func classifyImage(_ image: UIImage) async {
43 isProcessing = true
44 defer { isProcessing = false }
45 
46 guard let ciImage = CIImage(image: image) else { return }
47 
48 do {
49 let config = MLModelConfiguration()
50 config.computeUnits = .all
51 let classifier = try MobileNetV2(configuration: config)
52 
53 let handler = VNImageRequestHandler(ciImage: ciImage)
54 let request = VNCoreMLRequest(model: try VNCoreMLModel(for: classifier.model))
55 
56 try handler.perform([request])
57 
58 if let results = request.results as? [VNClassificationObservation],
59 let topResult = results.first {
60 classificationResult = topResult.identifier
61 confidence = Double(topResult.confidence)
62 }
63 } catch {
64 classificationResult = "Hata: \(error.localizedDescription)"
65 }
66 }
67}

6. Performance Optimizasyonu

Model inference performansi icin dikkat edilmesi gerekenler:

  1. Batch Prediction: Birden fazla input'u tek seferde isleyin
  2. Model Warmup: Ilk prediction yavas olabilir, app launch'ta warmup yapin
  3. Background Thread: Ana thread'i bloklamayin
  4. Model Caching: Modeli bir kez yukleyip tekrar kullanin

Easter Egg

Gizli bir bilgi buldun!

Bu bölümde gizli bir bilgi var. Keşfetmek ister misin?

7. Model Boyutu Kucultme

Teknik
Boyut Azaltma
Dogruluk Kaybi
Float16 Quantization
%50
Minimal
Int8 Quantization
%75
Dusuk
Palettization (4-bit)
%87
Orta
Pruning + Quantization
%90+
Degisken
Knowledge Distillation
%60-80
Dusuk

ALTIN İPUCU

Bu yazının en değerli bilgisi

Bu ipucu, yazının en önemli çıkarımını içeriyor.

Okuyucu Ödülü

Tebrikler! Bu yazıyı sonuna kadar okuduğun için sana özel bir hediyem var:

10. Sonuc ve Oneriler

On-device ML, iOS uygulamalarinda yeni bir cag aciyor. Apple'in Neural Engine'i her yil daha gucleniyor ve Core ML framework'u surekli yeni ozellikler kazaniyor. Kucuk modellerle baslayip, kullanici deneyimini olcumleyerek buyuyun. Gizlilik avantajini pazarlamada kullanmayi unutmayin — kullanicilar verilerinin cihazda kaldigini bilmek istiyor.

Bir sonraki adim olarak Create ML ile kendi modelinizi egitmeyi deneyin. Goruntu siniflandirma veya metin analizi gibi basit bir gorevle baslayip, zamanla daha karmasik modellere gecebilirsiniz.

Etiketler

#Machine Learning#Core ML#Neural Engine#On-Device#iOS#AI
Muhittin Çamdalı

Muhittin Çamdalı

Senior iOS Developer

12+ yıllık deneyime sahip iOS Developer. Swift, SwiftUI ve modern iOS mimarileri konusunda uzman. Apple platformlarında performanslı ve kullanıcı dostu uygulamalar geliştiriyorum.

iOS Geliştirme Haberleri

Haftalık Swift tips, SwiftUI tricks ve iOS best practices. Spam yok, sadece değerli içerik.

Gizliliğinize saygı duyuyoruz. İstediğiniz zaman abonelikten çıkabilirsiniz.

Paylaş

Bunu da begenebilirsiniz