Search icon CANCEL
Subscription
0
Cart icon
Your Cart (0 item)
Close icon
You have no products in your basket yet
Save more on your purchases! discount-offer-chevron-icon
Savings automatically calculated. No voucher code required.
Arrow left icon
Explore Products
Best Sellers
New Releases
Books
Videos
Audiobooks
Learning Hub
Newsletter Hub
Free Learning
Arrow right icon
timer SALE ENDS IN
0 Days
:
00 Hours
:
00 Minutes
:
00 Seconds
Machine Learning with Swift
Machine Learning with Swift

Machine Learning with Swift: Artificial Intelligence for iOS

Arrow left icon
Profile Icon Alexander Sosnovshchenko Profile Icon Jojo Moolayil Profile Icon Oleksandr Baiev
Arrow right icon
€8.99 €26.99
Full star icon Full star icon Full star icon Empty star icon Empty star icon 3 (1 Ratings)
eBook Feb 2018 378 pages 1st Edition
eBook
€8.99 €26.99
Paperback
€32.99
Subscription
Free Trial
Renews at €18.99p/m
Arrow left icon
Profile Icon Alexander Sosnovshchenko Profile Icon Jojo Moolayil Profile Icon Oleksandr Baiev
Arrow right icon
€8.99 €26.99
Full star icon Full star icon Full star icon Empty star icon Empty star icon 3 (1 Ratings)
eBook Feb 2018 378 pages 1st Edition
eBook
€8.99 €26.99
Paperback
€32.99
Subscription
Free Trial
Renews at €18.99p/m
eBook
€8.99 €26.99
Paperback
€32.99
Subscription
Free Trial
Renews at €18.99p/m

What do you get with eBook?

Product feature icon Instant access to your Digital eBook purchase
Product feature icon Download this book in EPUB and PDF formats
Product feature icon Access this title in our online reader with advanced features
Product feature icon DRM FREE - Read whenever, wherever and however you want
OR
Modal Close icon
Payment Processing...
tick Completed

Billing Address

Table of content icon View table of contents Preview book icon Preview Book

Machine Learning with Swift

Classification – Decision Tree Learning

In the previous chapter, we discussed different types of machine learning, including supervised classification tasks; in this chapter, we will build our first Swift application for this. We will discuss main components of machine learning development stack, and will also exercise in data generation, exploratory analysis, preprocessing, and models training and evaluation in Python. After this, we will transfer our model to Swift. We will also discuss a specific class of supervised learning algorithms—decision tree learning and its extension: random forest.

The following topics are waiting for us in this chapter:

  • Machine learning software development stack
  • Python toolbox for machine learning: IPython, SciPy, scikit-learn
  • Dataset generation and exploratory analysis
  • Data preprocessing
  • Decision tree learning and random forest
  • Assessing...

Machine learning toolbox

For many years, the programming language of choice for machine learning was one of the following: Python, R, MATLAB, C++. This is not due to some specific language features, but because of the infrastructure around it: libraries and tools. Swift is a relatively young programming language, and anyone who chooses it as a primary tool for machine learning development should start from the very basic building blocks, and build his own tools and libraries. Recently, Apple became more open to third-party Python machine learning tools: Core ML can work with some of them.

Here is a list of components that are needed for the successful machine learning research and development, and examples of popular libraries and tools of the type:

  • Linear algebra: Machine learning developer needs data structures like vectors, matrices, and tensors with compact syntax and hardware...

Prototyping the first machine learning app

Usually, before implementing a machine learning application for mobile devices, you want to do a quick and dirty prototype just to check your ideas. This allows to save a lot of time when you realize that the model you initially thought works perfectly for your problem, in reality doesn't. The quickest way to do a prototype is to use Python or R tools listed in the previous section.

Python is a general-purpose programming language with rich infrastructure and vibrant community. Its syntax is similar in many ways to Swift's one. Throughout this book, we'll use it for prototyping, and Swift for actual development.

When you have tested your ideas and a model prototype works as you expect, you can start thinking about how to port it to an iOS. You have several options here:

Inference-only options:

  • Check the Core ML, and a...

IPython notebook crash course

Feel free to skip this section if you're familiar with the Python and Jupyter notebooks.

IPython notebook and its web-based GUI Jupyter are standard tools for data-driven machine learning development. Jupyter is also a handy tool for learning Python and its libraries. You can combine pieces of code with comments in markdown format. You can also execute pieces of code in place, chaining them one after another, and immediately seeing the results of computations. It also allows to embed interactive charts, tables, videos, and other multimedia objects inside the notebook. We will use Jupyter notebooks for writing quick prototypes of our models.

To create a new notebook, run in the Terminal:

> jupyter notebook  

You will see output similar to this:

[I 10:51:23.269 NotebookApp] Serving notebooks from local directory: ...
[I 10:51:23.269 NotebookApp...

Time to practice

In the following sections, we'll dive into machine learning practice, to get a feeling of what it looks like. Just like in a theater play, in machine learning you have a list of characters and a list of acts.

Two main characters are:

  • Dataset
  • Model

Three main acts are:

  • Dataset preparation
  • Model training
  • Model evaluation

We'll go through all these acts, and by the end of the chapter we'll have our first trained model. First, we need to define a problem, and then we can start coding a prototype in Python. Our destination point is a working model in Swift. Don't take the problem itself too seriously, though, because as the first exercise, we're going to solve a fictional problem.

Machine learning for extra-terrestrial life explorers

Swift is undoubtedly the programming language of the future. In the nearest years, we're expecting to see Swift being employed to program-intelligent scout robots that will explore alien planets and life forms on them. These robots should be able to recognize and classify aliens they will encounter. Let's build a model to distinguish between two alien species using their characteristic features.

The biosphere of the distant planet consists mainly of two species: night predators rabbosauruses, and peaceful, herbivorous platyhogs (see the following diagram). Roboscouts are equipped with sensors to measure only three features of each individual: length (in meters), color, and fluffiness.

Figure 2.1: Objects of interest in our first machine learning task. Picture by Mykola Sosnovshchenko.
The full code of the Python...

Loading the dataset

Create and open a new IPython notebook. In the chapter's supplementary materials, you can see the file extraterrestrials.csv. Copy it to the same folder where you created your notebook. In the first cell of your notebook, execute the magical command:

In []: 
%matplotlib inline 

This is needed to see inline plots right in the notebook in the future.

The library we are using for datasets loading and manipulation is pandas. Let's import it, and load the .csv file:

In []: 
import pandas as pd 
df = pd.read_csv('extraterrestrials.csv', sep='t', encoding='utf-8', index_col=0) 

Object df is a data frame. This is a table-like data structured for efficient manipulations over the different data types. To see what's inside, execute:

In []: 
df.head() 
Out[]: 

Length

Color

Fluffy

Label

0

27.545139

Pink gold...

Exploratory data analysis

First, we want to see how many individuals of each class we have. This is important, because if the class distribution is very imbalanced (like 1 to 100, for example), we will have problems training our classification models. You can get data frame columns via the dot notation. For example, df.label will return you the label column as a new data frame. The data frame class has all kinds of useful methods for calculating the summary statistics. The value_counts() method returns the counts of each element type in the data frame:

In []: 
df.label.value_counts() 
Out[]: 
platyhog       520 
rabbosaurus    480 
Name: label, dtype: int64 

The class distribution looks okay for our purposes. Now let's explore the features.

We need to group our data by classes, and calculate feature statistics separately to see the difference between the creature...

Machine learning toolbox


For many years, the programming language of choice for machine learning was one of the following: Python, R, MATLAB, C++. This is not due to some specific language features, but because of the infrastructure around it: libraries and tools. Swift is a relatively young programming language, and anyone who chooses it as a primary tool for machine learning development should start from the very basic building blocks, and build his own tools and libraries. Recently, Apple became more open to third-party Python machine learning tools: Core ML can work with some of them.

Here is a list of components that are needed for the successful machine learning research and development, and examples of popular libraries and tools of the type:

  • Linear algebra: Machine learning developer needs data structures like vectors, matrices, and tensors with compact syntax and hardware-accelerated operations on them. Examples in other languages: NumPy, MATLAB, and R standard libraries, Torch.
  • Probability...

Prototyping the first machine learning app


Usually, before implementing a machine learning application for mobile devices, you want to do a quick and dirty prototype just to check your ideas. This allows to save a lot of time when you realize that the model you initially thought works perfectly for your problem, in reality doesn't. The quickest way to do a prototype is to use Python or R tools listed in the previous section.

Python is a general-purpose programming language with rich infrastructure and vibrant community. Its syntax is similar in many ways to Swift's one. Throughout this book, we'll use it for prototyping, and Swift for actual development.

When you have tested your ideas and a model prototype works as you expect, you can start thinking about how to port it to an iOS. You have several options here:

Inference-only options:

  • Check the Core ML, and a list of the Python libraries it supports. Maybe, you will be able to export your model in Core ML format, and run it on a device.
  • Write...

IPython notebook crash course


Feel free to skip this section if you're familiar with the Python and Jupyter notebooks.

IPython notebook and its web-based GUI Jupyter are standard tools for data-driven machine learning development. Jupyter is also a handy tool for learning Python and its libraries. You can combine pieces of code with comments in markdown format. You can also execute pieces of code in place, chaining them one after another, and immediately seeing the results of computations. It also allows to embed interactive charts, tables, videos, and other multimedia objects inside the notebook. We will use Jupyter notebooks for writing quick prototypes of our models.

To create a new notebook, run in the Terminal:

> jupyter notebook

You will see output similar to this:

[I 10:51:23.269 NotebookApp] Serving notebooks from local directory: ...[I 10:51:23.269 NotebookApp] 0 active kernels [I 10:51:23.270 NotebookApp] The Jupyter Notebook is running at: http://localhost:8888/?token=3c073db5636e366fd750e661cc597652025fdbf41162c125...

Time to practice


In the following sections, we'll dive into machine learning practice, to get a feeling of what it looks like. Just like in a theater play, in machine learning you have a list of characters and a list of acts.

Two main characters are:

  • Dataset
  • Model

Three main acts are:

  • Dataset preparation
  • Model training
  • Model evaluation

We'll go through all these acts, and by the end of the chapter we'll have our first trained model. First, we need to define a problem, and then we can start coding a prototype in Python. Our destination point is a working model in Swift. Don't take the problem itself too seriously, though, because as the first exercise, we're going to solve a fictional problem.

Machine learning for extra-terrestrial life explorers


Swift is undoubtedly the programming language of the future. In the nearest years, we're expecting to see Swift being employed to program-intelligent scout robots that will explore alien planets and life forms on them. These robots should be able to recognize and classify aliens they will encounter. Let's build a model to distinguish between two alien species using their characteristic features.

The biosphere of the distant planet consists mainly of two species: night predators rabbosauruses, and peaceful, herbivorous platyhogs (see the following diagram). Roboscouts are equipped with sensors to measure only three features of each individual: length (in meters), color, and fluffiness.

Figure 2.1: Objects of interest in our first machine learning task. Picture by Mykola Sosnovshchenko.

Note

The full code of the Python part of this chapter can be found here: ML_Intro.ipynb.

Loading the dataset


Create and open a new IPython notebook. In the chapter's supplementary materials, you can see the file extraterrestrials.csv. Copy it to the same folder where you created your notebook. In the first cell of your notebook, execute the magical command:

In []: 
%matplotlib inline 

This is needed to see inline plots right in the notebook in the future.

The library we are using for datasets loading and manipulation is pandas. Let's import it, and load the .csv file:

In []: 
import pandas as pd 
df = pd.read_csv('extraterrestrials.csv', sep='t', encoding='utf-8', index_col=0) 

Object df is a data frame. This is a table-like data structured for efficient manipulations over the different data types. To see what's inside, execute:

In []: 
df.head() 
Out[]: 

Length

Color

Fluffy

Label

0

27.545139

Pink gold

True

Rabbosaurus

1

12.147357

Pink gold

False

Platyhog

2

23.454173

Light black

True

Rabbosaurus

3

29.956698

Pink gold

True

Rabbosaurus

4

34.884065

Light black

True

Rabbosaurus

This prints the first five rows of the...

Exploratory data analysis


First, we want to see how many individuals of each class we have. This is important, because if the class distribution is very imbalanced (like 1 to 100, for example), we will have problems training our classification models. You can get data frame columns via the dot notation. For example, df.label will return you the label column as a new data frame. The data frame class has all kinds of useful methods for calculating the summary statistics. The value_counts() method returns the counts of each element type in the data frame:

In []: 
df.label.value_counts() 
Out[]: 
platyhog       520 
rabbosaurus    480 
Name: label, dtype: int64 

The class distribution looks okay for our purposes. Now let's explore the features.

We need to group our data by classes, and calculate feature statistics separately to see the difference between the creature classes. This can be done using the groupby() method. It takes the label of the column by which you want to group your data:

In [...
Left arrow icon Right arrow icon
Download code icon Download Code

Key benefits

  • Implement effective machine learning solutions for your iOS applications
  • Use Swift and Core ML to build and deploy popular machine learning models
  • Develop neural networks for natural language processing and computer vision

Description

Machine learning as a field promises to bring increased intelligence to the software by helping us learn and analyse information efficiently and discover certain patterns that humans cannot. This book will be your guide as you embark on an exciting journey in machine learning using the popular Swift language. We’ll start with machine learning basics in the first part of the book to develop a lasting intuition about fundamental machine learning concepts. We explore various supervised and unsupervised statistical learning techniques and how to implement them in Swift, while the third section walks you through deep learning techniques with the help of typical real-world cases. In the last section, we will dive into some hard core topics such as model compression, GPU acceleration and provide some recommendations to avoid common mistakes during machine learning application development. By the end of the book, you'll be able to develop intelligent applications written in Swift that can learn for themselves.

Who is this book for?

iOS developers who wish to create smarter iOS applications using the power of machine learning will find this book to be useful. This book will also benefit data science professionals who are interested in performing machine learning on mobile devices. Familiarity with Swift programming is all you need to get started with this book.

What you will learn

  • Learn rapid model prototyping with Python and Swift
  • Deploy pre-trained models to iOS using Core ML
  • Find hidden patterns in the data using unsupervised learning
  • Get a deeper understanding of the clustering techniques
  • Learn modern compact architectures of neural networks for iOS devices
  • Train neural networks for image processing and natural language processing

Product Details

Country selected
Publication date, Length, Edition, Language, ISBN-13
Publication date : Feb 28, 2018
Length: 378 pages
Edition : 1st
Language : English
ISBN-13 : 9781787123526
Category :
Languages :
Tools :

What do you get with eBook?

Product feature icon Instant access to your Digital eBook purchase
Product feature icon Download this book in EPUB and PDF formats
Product feature icon Access this title in our online reader with advanced features
Product feature icon DRM FREE - Read whenever, wherever and however you want
OR
Modal Close icon
Payment Processing...
tick Completed

Billing Address

Product Details

Publication date : Feb 28, 2018
Length: 378 pages
Edition : 1st
Language : English
ISBN-13 : 9781787123526
Category :
Languages :
Tools :

Packt Subscriptions

See our plans and pricing
Modal Close icon
€18.99 billed monthly
Feature tick icon Unlimited access to Packt's library of 7,000+ practical books and videos
Feature tick icon Constantly refreshed with 50+ new titles a month
Feature tick icon Exclusive Early access to books as they're written
Feature tick icon Solve problems while you work with advanced search and reference features
Feature tick icon Offline reading on the mobile app
Feature tick icon Simple pricing, no contract
€189.99 billed annually
Feature tick icon Unlimited access to Packt's library of 7,000+ practical books and videos
Feature tick icon Constantly refreshed with 50+ new titles a month
Feature tick icon Exclusive Early access to books as they're written
Feature tick icon Solve problems while you work with advanced search and reference features
Feature tick icon Offline reading on the mobile app
Feature tick icon Choose a DRM-free eBook or Video every month to keep
Feature tick icon PLUS own as many other DRM-free eBooks or Videos as you like for just €5 each
Feature tick icon Exclusive print discounts
€264.99 billed in 18 months
Feature tick icon Unlimited access to Packt's library of 7,000+ practical books and videos
Feature tick icon Constantly refreshed with 50+ new titles a month
Feature tick icon Exclusive Early access to books as they're written
Feature tick icon Solve problems while you work with advanced search and reference features
Feature tick icon Offline reading on the mobile app
Feature tick icon Choose a DRM-free eBook or Video every month to keep
Feature tick icon PLUS own as many other DRM-free eBooks or Videos as you like for just €5 each
Feature tick icon Exclusive print discounts

Frequently bought together


Stars icon
Total 106.97
Reactive Programming with Swift 4
€36.99
Hands-On Full-Stack Development with Swift
€36.99
Machine Learning with Swift
€32.99
Total 106.97 Stars icon
Banner background image

Table of Contents

13 Chapters
Getting Started with Machine Learning Chevron down icon Chevron up icon
Classification – Decision Tree Learning Chevron down icon Chevron up icon
K-Nearest Neighbors Classifier Chevron down icon Chevron up icon
K-Means Clustering Chevron down icon Chevron up icon
Association Rule Learning Chevron down icon Chevron up icon
Linear Regression and Gradient Descent Chevron down icon Chevron up icon
Linear Classifier and Logistic Regression Chevron down icon Chevron up icon
Neural Networks Chevron down icon Chevron up icon
Convolutional Neural Networks Chevron down icon Chevron up icon
Natural Language Processing Chevron down icon Chevron up icon
Machine Learning Libraries Chevron down icon Chevron up icon
Optimizing Neural Networks for Mobile Devices Chevron down icon Chevron up icon
Best Practices Chevron down icon Chevron up icon

Customer reviews

Rating distribution
Full star icon Full star icon Full star icon Empty star icon Empty star icon 3
(1 Ratings)
5 star 0%
4 star 0%
3 star 100%
2 star 0%
1 star 0%
Me Apr 28, 2018
Full star icon Full star icon Full star icon Empty star icon Empty star icon 3
Just a few minutes into the examples and walk-throughs and I'm running into errors and oversights. I hope the entire book isn't like this. I buy technical books to save time, not spend more time debugging misdirections. So far the issues are minor and have only cost about an hour to resolve, and perhaps less for someone who regularly works with the prescribed tools, but again, the point is to guide the user off a cliff... I mean through the material.
Amazon Verified review Amazon
Get free access to Packt library with over 7500+ books and video courses for 7 days!
Start Free Trial

FAQs

How do I buy and download an eBook? Chevron down icon Chevron up icon

Where there is an eBook version of a title available, you can buy it from the book details for that title. Add either the standalone eBook or the eBook and print book bundle to your shopping cart. Your eBook will show in your cart as a product on its own. After completing checkout and payment in the normal way, you will receive your receipt on the screen containing a link to a personalised PDF download file. This link will remain active for 30 days. You can download backup copies of the file by logging in to your account at any time.

If you already have Adobe reader installed, then clicking on the link will download and open the PDF file directly. If you don't, then save the PDF file on your machine and download the Reader to view it.

Please Note: Packt eBooks are non-returnable and non-refundable.

Packt eBook and Licensing When you buy an eBook from Packt Publishing, completing your purchase means you accept the terms of our licence agreement. Please read the full text of the agreement. In it we have tried to balance the need for the ebook to be usable for you the reader with our needs to protect the rights of us as Publishers and of our authors. In summary, the agreement says:

  • You may make copies of your eBook for your own use onto any machine
  • You may not pass copies of the eBook on to anyone else
How can I make a purchase on your website? Chevron down icon Chevron up icon

If you want to purchase a video course, eBook or Bundle (Print+eBook) please follow below steps:

  1. Register on our website using your email address and the password.
  2. Search for the title by name or ISBN using the search option.
  3. Select the title you want to purchase.
  4. Choose the format you wish to purchase the title in; if you order the Print Book, you get a free eBook copy of the same title. 
  5. Proceed with the checkout process (payment to be made using Credit Card, Debit Cart, or PayPal)
Where can I access support around an eBook? Chevron down icon Chevron up icon
  • If you experience a problem with using or installing Adobe Reader, the contact Adobe directly.
  • To view the errata for the book, see www.packtpub.com/support and view the pages for the title you have.
  • To view your account details or to download a new copy of the book go to www.packtpub.com/account
  • To contact us directly if a problem is not resolved, use www.packtpub.com/contact-us
What eBook formats do Packt support? Chevron down icon Chevron up icon

Our eBooks are currently available in a variety of formats such as PDF and ePubs. In the future, this may well change with trends and development in technology, but please note that our PDFs are not Adobe eBook Reader format, which has greater restrictions on security.

You will need to use Adobe Reader v9 or later in order to read Packt's PDF eBooks.

What are the benefits of eBooks? Chevron down icon Chevron up icon
  • You can get the information you need immediately
  • You can easily take them with you on a laptop
  • You can download them an unlimited number of times
  • You can print them out
  • They are copy-paste enabled
  • They are searchable
  • There is no password protection
  • They are lower price than print
  • They save resources and space
What is an eBook? Chevron down icon Chevron up icon

Packt eBooks are a complete electronic version of the print edition, available in PDF and ePub formats. Every piece of content down to the page numbering is the same. Because we save the costs of printing and shipping the book to you, we are able to offer eBooks at a lower cost than print editions.

When you have purchased an eBook, simply login to your account and click on the link in Your Download Area. We recommend you saving the file to your hard drive before opening it.

For optimal viewing of our eBooks, we recommend you download and install the free Adobe Reader version 9.