Core ML Survival Guide
Core ML Survival Guide
More than you ever wanted to know about mlmodel files and the Core ML and Vision APIs
About the Book
New: 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.
Reader Testimonials
Dror Yaffe
http://bazaart.me
Very clear and concise explanations, thanks for compiling all this knowledge, I'm sure it will help many others as well.
Matthieu Rouif
I just wanted to say a huge thank you for you book, your blog posts and your tips. I just launched BG (https://itunes.apple.com/us/app/bg-eraser/id1455009060?mt=8) and none of it would have happen without you or at least it would have taken 2x more time.
Steve Jenkins
Founder, myshotcount.com
Matthijs is not only an authority on iOS and ML, he embodies a give first attitude. I highly recommend Matthijs and his book.
Hendrik Kueck
juxtaposerapp.com
Your CoreML book really helped me a lot. Thank you for writing it and keeping it updated! I don’t think I would have figured out how to convert my PyTorch models to CoreML without it (specifically converting bilinear upsampling layers).
Paprika
This is a wonderful book. I've done iOS app development (and Windows, Android, and Mac dev) for maybe 11 years now, and this is the best, most comprehensive Apple ecosystem tech book I've come across. It's not only well-organized and lucid but I'm gobbling up all the content in it, since Core ML is one of the most opaque Apple frameworks I've come across. Very much worth the money... you've saved me a huge amount of effort.
Table of Contents
-
- About the Author
- Introduction
- Who Is This Book For?
- Useful Links
-
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
-
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
-
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
-
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
-
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
-
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
-
Part 7: On-device Personalization
- What is on-device personalization?
- Making a Model Updatable
- Training a Neural Network
- k-Nearest Neighbors
Authors have earned$9,882,857writing, publishing and selling on Leanpub, earning 80% royalties while saving up to 25 million pounds of CO2 and up to 46,000 trees.
Learn more about writing on Leanpub
The Leanpub 45-day 100% Happiness Guarantee
Within 45 days of purchase you can get a 100% refund on any Leanpub purchase, in two clicks.
See full terms
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), EPUB (for phones and tablets) and MOBI (for 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
Top Books
C++ Best Practices
Jason TurnerLevel up your C++, get the tools working for you, eliminate common problems, and move on to more exciting things!
Functional Design and Architecture
Alexander GraninSoftware Design in Functional Programming, Design Patterns and Practices, Methodologies and Application Architectures. How to build real software in Haskell with less efforts and low risks. The first complete source of knowledge.
OpenIntro Statistics
David Diez, Christopher Barr, Mine Cetinkaya-Rundel, and OpenIntroA complete foundation for Statistics, also serving as a foundation for Data Science.
Leanpub revenue supports OpenIntro (US-based nonprofit) so we can provide free desk copies to teachers interested in using OpenIntro Statistics in the classroom and expand the project to support free textbooks in other subjects.
More resources: openintro.org.
R Programming for Data Science
Roger D. PengThis book brings the fundamentals of R programming to you, using the same material developed as part of the industry-leading Johns Hopkins Data Science Specialization. The skills taught in this book will lay the foundation for you to begin your journey learning data science. Printed copies of this book are available through Lulu.
C++20
Rainer GrimmC++20 is the next big C++ standard after C++11. As C++11 did it, C++20 changes the way we program modern C++. This change is, in particular, due to the big four of C++20: ranges, coroutines, concepts, and modules.
I am a Software Engineer and I am in Charge
Alexis Monville and Michael DoyleI am a Software Engineer and I am in Charge is a real-world, practical book that helps you increase your impact and satisfaction at work no matter who you work with.
In the book, we will follow Sandrine, a fictional character who learns to think in a new way enabling her to take a different course of action.
Invest In Digital Health - The Medical Futurist's Guide
Dr. Bertalan MeskoArtificial Intelligence and Digital Health are booming. In this book, we explain why now it's a good time to invest in Digital Health and give recommendations on where to invest by looking at the top 24 technological trends we find the most promising.
Atomic Kotlin
Bruce Eckel and Svetlana IsakovaFor both beginning and experienced programmers! From the author of the multi-award-winning Thinking in C++ and Thinking in Java together with a member of the Kotlin language team comes a book that breaks the concepts into small, easy-to-digest "atoms," along with exercises supported by hints and solutions directly inside IntelliJ IDEA!
The Hundred-Page Machine Learning Book
Andriy BurkovEverything you really need to know in Machine Learning in a hundred pages.
Mastering STM32
Carmine NovielloWith more than 600 microcontrollers, STM32 is probably the most complete ARM Cortex-M platform on the market. This book aims to be the first guide around that introduces the reader to this exciting MCU portfolio from ST Microelectronics and its official CubeHAL.
Top Bundles
- #1
Software Architecture for Developers: Volumes 1 & 2 - Technical leadership and communication
2 Books
"Software Architecture for Developers" is a practical and pragmatic guide to modern, lightweight software architecture, specifically aimed at developers. You'll learn:The essence of software architecture.Why the software architecture role should include coding, coaching and collaboration.The things that you really need to think about before... - #2
The Future of Digital Health
6 Books
We put together the most popular books from The Medical Futurist to provide a clear picture about the major trends shaping the future of medicine and healthcare. Digital health technologies, artificial intelligence, the future of 20 medical specialties, big pharma, data privacy and how technology giants such as Amazon or Google want to conquer... - #3
Cisco CCNA 200-301 Complet
4 Books
Ce lot comprend les quatre volumes du guide préparation à l'examen de certification Cisco CCNA 200-301. - #4
CCDE Practical Studies (All labs)
3 Books
CCDE lab - #5
"The C++ Standard Library" and "Concurrency with Modern C++"
2 Books
Get my books "The C++ Standard Library" and "Concurrency with Modern C++" in a bundle. The first book gives you the details you should know about the C++ standard library; the second one dives deeper into concurrency with modern C++. In sum, you get more than 600 pages full of modern C++ and about 250 source files presenting the standard library... - #6
Modern Management Made Easy
3 Books
Read all three Modern Management Made Easy books. Learn to manage yourself, lead and serve others, and lead the organization. - #7
Programming with Ease
3 Books
Alle drei Bände der Serie Programming with Ease in einem Paket. Darin findest du alles, was ich dir zu den wichtigsten Phasen der Softwareentwicklung im Hinblick auf Clean Code Development für langfristig hohe Produktivität sagen kann.Im Band Slicing findest du die Anforderungsanalyse im Rahmen eines iterativ-inkrementellen Vorgehensmodells aus... - #8
Vagrant Ansible
2 Books
Unveil the power of Ansible and Vagrant with this bundle at a special price. You'll have everything you need to get started with Vagrant - learn the basics and how to create your virtual development environments, using Ansible as provisioner! About Vagrant Cookbook Vagrant Cookbook is a complete guide to get started with Vagrant and create your... - #9
Mastering Containers
2 Books
Docker and Kubernetes are taking the world by storm! These books will get you up-to-speed fast! Docker Deep Dive is over 400 pages long, and covers all objectives on the Docker Certified Associate exam.The Kubernetes Book includes everything you need to get up and running with Kubernetes! - #10
Growing Agile: The Complete Coach's Guide
7 Books
Growing Agile: Coach's Guide Series This bundle provides a collection of training and workshop plans for a variety of agile topics. The series is aimed at agile coaches, trainers and ScrumMasters who often find themselves needing to help teams understand agile concepts. Each book in the series provides the plans, slides, handouts and activity...