Leanpub Header

Skip to main content

Core ML Survival Guide

More than you ever wanted to know about mlmodel files and the Core ML and Vision APIs

Core ML is pretty easy to use — except when it doesn’t do what you want. The Core ML Survival Guide is packed with tips and tricks for solving the most common Core ML problems. Updated for iOS 14 and macOS 11.

Minimum price

$39.99

$54.99

You pay

$54.99

Author earns

$43.99
$

...Or Buy With Credits!

You can get credits monthly with a Reader Membership
PDF
EPUB
WEB
656
Readers
505
Pages
About

About

About the Book

IMPORTANT: I will not be updating this book to the new features introduced with iOS 15 and macOS 12. Those new features are welcome improvements but they also make most of this book irrelevant. That being said, if you are targeting older versions of iOS or macOS, or you cannot use the new mlpackage format or the new ML Program models for some reason, the Core ML Survival Guide will still be useful. Thanks to all the readers for supporting this book over the years!

---

Last updated for iOS 14, macOS Big Sur, and coremltools 4.

Core ML has made it easier than ever to add machine learning to your iOS and macOS apps. Drag-and-drop an mlmodel file into your Xcode project, literally write two lines of code, and you’re done!

There are lots of tutorials that show how to get started with Core ML, but they only cover the very basics.

  • What if you want to do something more advanced?
  • What if you run into problems?
  • Where do you get Core ML models to begin with anyway?

Core ML may appear easy-to-use at first — but if you want to go beyond the basics, the learning curve suddenly becomes very steep. My goal with this book is to make the advanced features of Core ML accessible to everyone too.

I do machine learning on mobile for a living and I’ve been working with Core ML since it first came out. Every time I ran into a problem, I put the solution into a notes file. From posts on Stack Overflow, the Apple Developer Forums, and emails I receive from readers of my blog, it’s clear that other people are running into the same problems. So I collected my notes, cleaned them up, and put them into this book.

The Core ML Survival Guide contains pretty much everything I know about Core ML. With this book I hope to save you some time from having to figure out this stuff by yourself.

What you’ll learn:

  • How to best convert your models to Core ML. One of the biggest showstoppers happens right at the beginning: you’ve trained a model but the Core ML conversion fails. This book explains what to pay attention to when you’re training your models, and how you can convert troublesome models to Core ML anyway by writing your own converter. 
  • The mlmodel file format and what Core ML’s possibilities and limitations are. Understanding the internals of mlmodel files is useful to verify the model conversion was successful — but also for knowing how to design and train your models in the first place.
  • Model surgery. Lots of advice on how to fix problems with your mlmodel files and how to get the leanest — and fastest — Core ML models.
  • Tips for running the app on the device. It’s pretty easy to make predictions with Core ML once you have a model, but there are still some gotchas to watch out for. For example, you’ll want to verify the model really does what you expect it to! Also: how to make effective use of the new Neural Engine.
  • Working with CVPixelBuffer and MLMultiArray. When your model does more than just classification, you’ll need to understand how to read and write MLMultiArray objects. This part of the book shows effective methods for making MLMultiArray do what you want.
  • Advanced topics: Custom layers, custom models, building pipelines, working with video, using sequences, dynamic graphs, on-device training of models, and much more!

This book has 80+ chapters and is packed with tips and tricks. As I learn more about Core ML myself, I’ll keep updating the book so you’ll always have access to the most up-to-date knowledge about Core ML.

If Core ML is giving you trouble — or if you want to make the most out your Core ML models — then the Core ML Survival Guide is for you!

P.S. Also check out the chapter MobileNetV2 + SSDLite with Core ML on my blog to get a taste of what's in the book.

The source code for this book is available on GitHub.

Author

About the Author

Matthijs Hollemans

Matthijs Hollemans is a professional audio programmer. In his spare time he's a hobbyist musician who really needs to learn how to play the piano properly. Matthijs wrote the best-selling book The iOS Apprentice and is a co-author of Machine Learning by Tutorials from Kodeco (formerly raywenderlich.com). Check out his audio development blog at audiodev.blog.

Contents

Table of Contents

About the Author

Introduction

Who Is This Book For?

Useful Links

  1. Part 1: The Core ML Ecosystem

What is Core ML — and What is It Not?

Core ML Version History

The Vision Framework and Core ML

The SoundAnalysis Framework

Where to Get mlmodels?

Create ML: The Easiest Way to Train

Turi Create — it’s Like Create ML but in Python

coremltools

  1. Part 2: Converting Models

Image Preprocessing

Converting TensorFlow / PyTorch With the Unified API

Keras Conversion Tips

Converting tf.keras With the Old Converter

Caffe Conversion Tips

TensorFlow 1.x Conversion With tfcoreml

TensorFlow 2.x Conversion With coremltools 3

PyTorch Conversion Using ONNX

ONNX Conversion Tips

Torch7 Conversion Tips

MXNet Conversion Tips

Troubleshooting the Conversion Process

Writing Your Own Converter

NeuralNetworkBuilder

Model Training Tips

  1. Part 3: Examining Models

Viewing Models With Netron

Viewing Models With visualize_spec

The mlmodel File Format

Dynamic Tensor Shapes

Using the Spec to Edit Models

Looking Inside an mlmodel

Verifying the Conversion is Successful

Looking at Intermediate Layer Outputs

Checking the Layer Output Shapes

The mlmodel as a Big Text File

  1. Part 4: Model Surgery

Filling in the Metadata

Changing the Image Preprocessing Options

Using a Different Scale for Each Color Channel

Saving the Weights as 16-bit Floats

Quantizing the Weights

Changing the Input Type to Image

Outputting an Image Instead of a MultiArray

Outputting Floats Instead of Doubles

Tidying up MultiArray Shapes

Renaming Inputs and Outputs

Inserting a New Layer

Changing an Existing Layer

Deleting a Layer

Example: Cleaning Up a Converted Model (DeepLab v3+)

Replacing the Class Names of a Classifier

  1. Part 5: Inside the App

Understanding the Xcode-generated File

mlmodelc

Running the Core ML Compiler Manually

Downloading and Compiling Models on the Device

Running the Model on the CPU

The Neural Engine

CPU, GPU, or Neural Engine?

Inspecting the Model at Runtime

Making Sure the Input is Correct

Working With CVPixelBuffer

Using CGImage or Image Files Instead of CVPixelBuffer

Working With MLMultiArray

Reshaping an MLMultiArray

Transposing an MLMultiArray

Converting MLMultiArray to an Image

Converting from UIImage to MLMultiArray

Computing the Argmax

Translating Class Labels

  1. Part 6: Advanced Topics

Making Multiple Predictions at Once With Batches

Size Flexibility

Using the MLModel API

Vision FeaturePrint

Using Sequences

Creating Your Own Custom Layers

Creating Your Own Custom Models

Building Pipeline Models

Linked Models

Control Flow in Graphs

Working With Video

MobileNetV2 + SSDLite Example

Using Protobuf Without coremltools

Encrypting Models

Performance Tips

  1. Part 7: On-device Personalization

What is on-device personalization?

Making a Model Updatable

Training a Neural Network

k-Nearest Neighbors

Get the free sample chapters

Click the buttons to get the free sample in PDF or EPUB, or read the sample online here

The Leanpub 60 Day 100% Happiness Guarantee

Within 60 days of purchase you can get a 100% refund on any Leanpub purchase, in two clicks.

Now, this is technically risky for us, since you'll have the book or course files either way. But we're so confident in our products and services, and in our authors and readers, that we're happy to offer a full money back guarantee for everything we sell.

You can only find out how good something is by trying it, and because of our 100% money back guarantee there's literally no risk to do so!

So, there's no reason not to click the Add to Cart button, is there?

See full terms...

Earn $8 on a $10 Purchase, and $16 on a $20 Purchase

We pay 80% royalties on purchases of $7.99 or more, and 80% royalties minus a 50 cent flat fee on purchases between $0.99 and $7.98. You earn $8 on a $10 sale, and $16 on a $20 sale. So, if we sell 5000 non-refunded copies of your book for $20, you'll earn $80,000.

(Yes, some authors have already earned much more than that on Leanpub.)

In fact, authors have earned over $14 million writing, publishing and selling on Leanpub.

Learn more about writing on Leanpub

Free Updates. DRM Free.

If you buy a Leanpub book, you get free updates for as long as the author updates the book! Many authors use Leanpub to publish their books in-progress, while they are writing them. All readers get free updates, regardless of when they bought the book or how much they paid (including free).

Most Leanpub books are available in PDF (for computers) and EPUB (for phones, tablets and Kindle). The formats that a book includes are shown at the top right corner of this page.

Finally, Leanpub books don't have any DRM copy-protection nonsense, so you can easily read them on any supported device.

Learn more about Leanpub's ebook formats and where to read them

Write and Publish on Leanpub

You can use Leanpub to easily write, publish and sell in-progress and completed ebooks and online courses!

Leanpub is a powerful platform for serious authors, combining a simple, elegant writing and publishing workflow with a store focused on selling in-progress ebooks.

Leanpub is a magical typewriter for authors: just write in plain text, and to publish your ebook, just click a button. (Or, if you are producing your ebook your own way, you can even upload your own PDF and/or EPUB files and then publish with one click!) It really is that easy.

Learn more about writing on Leanpub