Creates a classifier from a training set represented by a dictionary.
SDKs
- macOS 10.14+
- Xcode 10.0+
Framework
- Create ML
Declaration
init(trainingData: [String : [URL]], parameters: MLImage Classifier.Model Parameters = ModelParameters(validationData: [:])) throws
Parameters
trainingData
The labeled images that you use to train the model. The keys of this dictionary represent the labels, while the values hold arrays of images that correspond to the given label.
parameters
Parameters that you use to configure model training.
Discussion
When you create an MLImage
instance, initialize it with an MLImage
structure. This allows you to configure the image classifier training process. For example, you can explicitly define the validation data set instead of allowing the model to choose a random selection of your training data. Alternatively, as shown in the following example, set validation
to nil
to allow the classifier to choose the validation data for you from among your training data. This lets you set other parameters—like maximum iterations and augmentation options—to non-default values:
let parameters = MLImageClassifier.ModelParameters(featureExtractor: .scenePrint(revision: 1),
validationData: nil,
maxIterations: 20,
augmentationOptions: [.crop])
For this particular initialization method—there’s another with the same signature but a different training data type—represent your training data with a dictionary that uses labels as keys. The corresponding values are arrays of URLs that indicate the images associated with that label. In this example, if you have elephant and giraffe images stored in a directory called Training
within your Downloads
directory, you can construct a dictionary with the URL of each image:
// Get the URL of the directory that holds the validation data.
guard let downloadsURL = FileManager.default.urls(for: .downloadsDirectory,
in: .userDomainMask).first
else { fatalError("Can't find Downloads directory") }
let url = downloadsURL.appendingPathComponent("Training")
// For a real classifier, use at least 10 images per label. More is better.
let trainingData = ["Elephant": [url.appendingPathComponent("Elephant.1.jpg"),
url.appendingPathComponent("Elephant.2.jpg")],
"Giraffe": [url.appendingPathComponent("Giraffe.1.jpg"),
url.appendingPathComponent("Giraffe.2.jpg")]]
Note
If you have training data in an MLImage
instance, use the similarly named init(training
instead. That initialization method takes a data source instead of a dictionary as its training data.
Use the parameter structure and training data to initialize the classifier. Training begins immediately.
let classifier = try MLImageClassifier(trainingData: trainingData,
parameters: parameters)