Skip to main content
coreydaley.dev
Docs menu

Train Create ML models from Swift code

The image and text classifiers, and most of Create ML’s other templates, are also in the CreateML Swift framework. A script is easier to rerun when the data changes, and you can keep it in version control next to the data. This one trains both models from the other pages, tests them and saves the .mlmodel files:

import CreateML
import Foundation
import TabularData

let data = URL(fileURLWithPath: CommandLine.arguments[1])
let out = URL(fileURLWithPath: CommandLine.arguments[2])

// Image classifier: a folder per label
let flowers = try MLImageClassifier(
    trainingData: .labeledDirectories(at: data.appending(path: "Flowers/Training")))
let imageTest = flowers.evaluation(
    on: .labeledDirectories(at: data.appending(path: "Flowers/Testing")))
print("Flowers test accuracy:", 1 - imageTest.classificationError)
print(imageTest.confusionDataFrame)
try flowers.write(to: out.appending(path: "FlowerClassifier.mlmodel"))

// Text classifier: JSON rows of {"text": ..., "label": ...}
let training = try DataFrame(contentsOfJSONFile: data.appending(path: "SupportMessages/training.json"))
let testing = try DataFrame(contentsOfJSONFile: data.appending(path: "SupportMessages/testing.json"))
let support = try MLTextClassifier(trainingData: training, textColumn: "text", labelColumn: "label")
let textTest = support.evaluation(on: testing, textColumn: "text", labelColumn: "label")
print("Support test accuracy:", 1 - textTest.classificationError)
try support.write(to: out.appending(path: "SupportClassifier.mlmodel"))

print(try support.prediction(from: "I was charged twice for my subscription this month."))

From the folder that holds train.swift, Flowers and SupportMessages, run it with that folder and a folder for the models:

mkdir -p models
xcrun swift train.swift . models

On my M2 Pro it took 44 seconds, almost all of it the flower photos:

Flowers test accuracy: 0.945280437756498
…
Support test accuracy: 0.9
billing

The image model scored 94.5% here against 93% in the app, on the same photos. Reruns gave between 94.3% and 94.8%: the validation photos it holds back are picked at random each time. (The app had also stopped early, at 19 of 25 iterations.)

A few things I ran into:

  • Use DataFrame, not MLDataTable, for text. The MLDataTable versions of MLTextClassifier’s initializer and evaluation still work but are deprecated, and so is the confusion table; use confusionDataFrame.
  • Settings are parameters. MLImageClassifier.ModelParameters sets iterations, augmentation and validation; MLTextClassifier.ModelParameters sets the algorithm (.maxEnt, or .transferLearning for the embedding options).
  • I only ran it on the Mac. Apple’s SDK also lists these classes for iOS and iPadOS 15 and later, for training on the device, which I didn’t try. Run the script with xcrun swift, as above.