Skip to content
All essays
iOSMarch 27, 202514 min

Advanced Swift Machine Learning: Custom Models

Build and train custom machine learning models in Swift. Create ML, training, and deployment.

Ü
Ümit Uz
Mobile & Full Stack Developer

Learn to build custom machine learning models with Create ML and deploy them to iOS apps.

Create ML Framework

Tabular Data Classification

swift
import CreateML
import Foundation

class TabularModelTrainer {
    func trainClassifier() async throws {
        // Load training data
        let dataURL = URL(fileURLWithPath: "/path/to/training-data.csv")

        do {
            let dataTable = try MLDataTable(contentsOf: dataURL)

            // Split data into training and testing
            let (trainingData, testingData) = dataTable.randomSplit(by: 0.8)

            // Train classifier
            let classifier = try MLClassifier(
                trainingData: trainingData,
                targetColumn: "category"
            )

            // Evaluate model
            let evaluationMetrics = try classifier.evaluation(on: testingData)

            print("Accuracy: \(evaluationMetrics.classificationError)")

            // Save model
            let metadata = MLModelMetadata(
                author: "Your Name",
                shortDescription: "Custom classifier",
                license: nil,
                version: "1.0"
            )

            let modelURL = URL(fileURLWithPath: "/path/to/Classifier.mlmodel")
            try classifier.write(to: modelURL, metadata: metadata)

        } catch {
            print("Training failed: \(error)")
        }
    }
}

Regression Model

swift
class RegressionModelTrainer {
    func trainRegressor() async throws {
        let dataURL = URL(fileURLWithPath: "/path/to/data.csv")

        do {
            let dataTable = try MLDataTable(contentsOf: dataURL)
            let (trainingData, testingData) = dataTable.randomSplit(by: 0.8)

            // Train regressor
            let regressor = try MLRegressor(
                trainingData: trainingData,
                targetColumn: "price"
            )

            // Evaluate
            let metrics = try regressor.evaluation(on: testingData)
            print("RMSE: \(metrics.rootMeanSquaredError)")

            // Save model
            let metadata = MLModelMetadata(
                author: "Your Name",
                shortDescription: "Price prediction model",
                license: nil,
                version: "1.0"
            )

            let modelURL = URL(fileURLWithPath: "/path/to/Regressor.mlmodel")
            try regressor.write(to: modelURL, metadata: metadata)

        } catch {
            print("Training failed: \(error)")
        }
    }
}

Image Classification

Custom Image Classifier

swift
class ImageClassifierTrainer {
    func trainImageClassifier() async throws {
        // Training data directory structure:
        // TrainingData/
        //   ├── Class1/
        //   │   ├── image1.jpg
        //   │   └── image2.jpg
        //   └── Class2/
        //       ├── image1.jpg
        //       └── image2.jpg

        let trainingDataURL = URL(fileURLWithPath: "/path/to/TrainingData")

        do {
            let model = try MLImageClassifier(
                trainingData: trainingDataURL,
                iterations: 10
            )

            // Save model
            let metadata = MLModelMetadata(
                author: "Your Name",
                shortDescription: "Custom image classifier",
                license: nil,
                version: "1.0"
            )

            let modelURL = URL(fileURLWithPath: "/path/to/ImageClassifier.mlmodel")
            try model.write(to: modelURL, metadata: metadata)

            print("Model trained successfully")

        } catch {
            print("Training failed: \(error)")
        }
    }
}

Text Classification

Text Classifier

swift
class TextClassifierTrainer {
    func trainTextClassifier() async throws {
        // Training data format:
        // text,label
        // "This is positive",positive
        // "This is negative",negative

        let dataURL = URL(fileURLWithPath: "/path/to/training-data.csv")

        do {
            let dataTable = try MLDataTable(contentsOf: dataURL)

            // Train text classifier
            let model = try MLTextClassifier(
                trainingData: dataTable,
                textColumn: "text",
                labelColumn: "label"
            )

            // Evaluate
            let (trainingMetrics, validationMetrics) = try model.trainingMetrics()

            print("Training accuracy: \(trainingMetrics.classificationError)")
            print("Validation accuracy: \(validationMetrics.classificationError)")

            // Save model
            let metadata = MLModelMetadata(
                author: "Your Name",
                shortDescription: "Sentiment analysis model",
                license: nil,
                version: "1.0"
            )

            let modelURL = URL(fileURLWithPath: "/path/to/TextClassifier.mlmodel")
            try model.write(to: modelURL, metadata: metadata)

        } catch {
            print("Training failed: \(error)")
        }
    }
}

Model Conversion

Convert to Core ML

swift
import CoreML

class ModelConverter {
    func convertModel(pythonModelURL: URL, outputPath: URL) throws {
        // Use coremltools Python package to convert:
        // import coremltools
        // coremltools.converters.keras.convert(
        //     'model.h5',
        //     input_name='input',
        //     output_name='output'
        // ).save('Model.mlmodel')

        // Then load in Swift
        let model = try MLModel(contentsOf: outputPath)
        print("Model converted successfully")
    }
}

On-Device Training

Personalized Model

swift
class PersonalizedModelTrainer {
    private var model: MLModel?

    func trainPersonalizedModel(userData: MLDataTable) async throws {
        // Create model updater
        let modelURL = Bundle.main.url(forResource: "BaseModel", withExtension: "mlmodel")!
        let baseModel = try MLModel(contentsOf: modelURL)

        // Update with user data
        let updatedModel = try MLModel(
            contentsOf: modelURL,
            configuration: MLModelConfiguration()
        )

        // Retrain with user data
        let retrainedModel = try MLRegressor(
            trainingData: userData,
            targetColumn: "target"
        )

        self.model = retrainedModel.model
    }

    func predict(input: [String: MLDataValue]) throws -> String {
        guard let model = model else {
            throw ModelError.modelNotAvailable
        }

        let inputFeatures = try MLDictionaryFeatureProvider(dictionary: input)
        let prediction = try model.prediction(from: inputFeatures)

        return prediction.description
    }

    enum ModelError: Error {
        case modelNotAvailable
    }
}

Model Optimization

Quantization

swift
class ModelOptimizer {
    func optimizeModel(modelURL: URL, outputPath: URL) throws {
        let model = try MLModel(contentsOf: modelURL)

        // Configure optimization
        let configuration = MLModelConfiguration()
        configuration.computeUnits = .all
        configuration.allowLowPrecisionAccumulationOnGPU = true

        // Save optimized model
        try model.write(to: outputPath)

        print("Model optimized successfully")
    }
}

Batch Prediction

Efficient Prediction

swift
class BatchPredictor {
    private let model: MLModel

    init(modelURL: URL) throws {
        self.model = try MLModel(contentsOf: modelURL)
    }

    func batchPredict(inputs: [[String: MLDataValue]]) throws -> [String] {
        var predictions: [String] = []

        for input in inputs {
            let featureProvider = try MLDictionaryFeatureProvider(dictionary: input)
            let prediction = try model.prediction(from: featureProvider)
            predictions.append(prediction.description)
        }

        return predictions
    }
}

Model Monitoring

Track Performance

swift
class ModelPerformanceMonitor {
    func trackPredictionAccuracy(predictions: [String], groundTruth: [String]) -> Double {
        let correct = zip(predictions, groundTruth).filter { $0 == $1 }.count
        return Double(correct) / Double(predictions.count)
    }

    func logPredictionMetrics(prediction: String, confidence: Double) {
        // Log to analytics
        print("Prediction: \(prediction), Confidence: \(confidence)")
    }
}

Best Practices

  1. 1Data Quality: Use high-quality training data
  2. 2Model Size: Optimize model for app size
  3. 3Performance: Test on real devices
  4. 4Privacy: Process data on-device
  5. 5Updates: Plan for model updates
  6. 6Fallback: Provide fallback for errors
  7. 7Testing: Test model thoroughly
  8. 8Monitoring: Track model performance

Advanced ML techniques enable powerful AI features in your apps!

Related essays

Next essay
Swift ARKit Guide: Augmented Reality Development