Building a Recommendation App With Create ML in SwiftUI

Learn how to train a model and how to give it prediction capability using Core ML and Create ML in SwiftUI. By Saeed Taheri.

Leave a rating/review
Download materials
Save for later
Share
You are currently viewing page 3 of 3 of this article. Click here to view the first page.

Showing Recommended T-shirts

In this section, you’ll sort the predicted results and show the first 10 items as the recommended t-shirts.

Immediately below your previous code, add this:

let sorted = zip(testData, predictionsColumn) // 1
  .sorted { lhs, rhs -> Bool in // 2
    lhs.1 > rhs.1
  }
  .filter { // 3
    $0.1 > 0
  }
  .prefix(10) // 4

Here’s a step-by-step breakdown of this code:

  1. Use zip(_:_:) to create a sequence of pairs built out of two underlying sequences: testData and predictionsColumn.
  2. Sort the newly created sequence based on the second parameter of the pair, aka the prediction value.
  3. Next, only keep the items for which the prediction value is positive. If you remember, the value of 1 for the favorite column means the user liked that specific t-shirt — 0 means undecided and -1 means disliked.
  4. You only keep the first 10 items but you could set it to show more or less. 10 is an arbitrary number.

Once you’ve got the first 10 recommended items, the next step is to add code to unzip and return instances of Shirt. Below the previous code, add the following:

let result = sorted.map(\.0.model)
continuation.resume(returning: result)

This code gets the first item of the pair using \.0, gets the model from FavoriteWrapper then resumes the continuation with the result.

You’ve come a long way!

The completed implementation for computeRecommendations(basedOn:) should look like this:

func computeRecommendations(basedOn items: [FavoriteWrapper<Shirt>]) async throws -> [Shirt] {
  return try await withCheckedThrowingContinuation { continuation in
    queue.async {
      #if targetEnvironment(simulator)
      continuation.resume(
        throwing: NSError(
          domain: "Simulator Not Supported", 
          code: -1
        )
      )
      #else
      let trainingData = items.filter {
        $0.isFavorite != nil
      }

      let trainingDataFrame = self.dataFrame(for: trainingData)

      let testData = items
      let testDataFrame = self.dataFrame(for: testData)

      do {
        let regressor = try MLLinearRegressor(
          trainingData: trainingDataFrame, 
          targetColumn: "favorite"
        )

        let predictionsColumn = (try regressor.predictions(from: testDataFrame))
        .compactMap { value in
          value as? Double
        }

        let sorted = zip(testData, predictionsColumn)
          .sorted { lhs, rhs -> Bool in
            lhs.1 > rhs.1
          }
          .filter {
            $0.1 > 0
          }
          .prefix(10)

        let result = sorted.map(\.0.model)
        continuation.resume(returning: result)
      } catch {
        continuation.resume(throwing: error)
      }
      #endif
    }
  }
}

Build and run. Try swiping something. You’ll see the recommendations row update each time you swipe left or right.

Updating recommendations row after each swipe

Where to Go From Here?

Click the Download Materials button at the top or bottom of this tutorial to download the final project for this tutorial.

In this tutorial, you learned:

  • A little of Create ML’s capabilities.
  • How to build and train a machine learning model.
  • How to use your model to make predictions based on user actions.

Machine learning is changing the way the world works, and it goes far beyond helping you pick the perfect t-shirt!

Most apps and services use ML to curate your feeds, make suggestions, and learn how to improve your experience. And it is capable of so much more — the concepts and applications in the ML world are broad.

ML has made today’s apps far smarter than the apps that delighted us in the early days of smartphones. It wasn’t always this easy to implement though — investments in data science, ultra-fast cloud computing, cheaper and faster storage, and an abundance of fresh data thanks to all these smartphones have allowed this world-changing technology to be democratized over the last decade.

Create ML is a shining example of how far this tech has come.

People spend years in universities to become professionals. But you can learn a lot about it without leaving your home. And you can put it to use in your app without having to first become an expert.

To explore the framework you just used, see Create ML Tutorial: Getting Started.

For a more immersive experience ML for mobile app developers, see our book Machine Learning by Tutorials.

You could also dive into ML by taking Supervised Machine Learning: Regression and Classification on Coursera. The instructor, Andrew Ng, is a Stanford professor and renowned by the ML community.

For ML on Apple platforms, you can always consult the documentation for Core ML and Create ML.

Moreover, Apple provides a huge number of videos on the subject. Watch some video sessions from Build dynamic iOS apps with the Create ML framework from WWDC 21 and What’s new in Create ML from WWDC 22.

Do you have any questions or comments? If so, please join the discussion in the forums below.