Simple Machine Learning App Using Apple’s Core ML Models

Step 1: Create new Xcode project

Step 2: Simple UI

For the project we’ll use a very simple layout, at first you will need a placeholder for your digit, then two buttons for clearing the canvas and for recognizing the digits.

Simple UI for Demo Project

Step 3: Set up the Vision Model

To detect your digits we’ll use the Vision Framework, the Vision Framework performs different kind of detections so you can even use it to detect your face, barcodes, images, and so on. To request our analysis we’ll use VNCoreMLRequest which will take our model and a completionHandler.

func setupVision() {  guard let visionModel = try? VNCoreMLModel(for: MNIST().model)   
else {fatalError(“can not load Vision ML model”)}
let classificationRequest = VNCoreMLRequest(model: visionModel,
completionHandler: self.handleClassification)
self.requests = [classificationRequest]}

Step 4: Create a completionHandler

At last, we’ll create our completionHandler, in this function we’ll request our VNCoreMLRequest and if there are any errors we’ll print them.

func handleClassification (request:VNRequest, error:Error?) {  guard let observations = request.results else {print(“no  
results”); return}
let classifications = observations
.flatMap({$0 as? VNClassificationObservation})
.filter({$0.confidence > 0.8})
.map({$0.identifier})
DispatchQueue.main.async {
self.digitLabel.text = classifications.first
}
}

Result

--

--

Get the Medium app

A button that says 'Download on the App Store', and if clicked it will lead you to the iOS App store
A button that says 'Get it on, Google Play', and if clicked it will lead you to the Google Play store