Tap into the Unique Capability of Core ML
Machine learning refers to the application of giving the computer the capability to learn without being programmed. Today, Core ML is the machine learning framework available for new iPhone that allows you to integrate ML models into your app. With Apple’s Core ML, developers are now able to build features, like text prediction, natural language processing, image recognition, etc. easily and conveniently.
Core ML is known as the newest foundational framework of machine learning used across a variety of Apple products, which include QuickType, Siri, and Camera. It provides remarkably fast performance with a smooth and easy integration of impressive machine learning models, allowing you to build apps with new features with the use of just a few code lines.
What are the Advantages of Core ML?
This new machine learning framework supports deep learning with more than thirty layer types. In addition, it supports some standards models, including SVMs, tree ensembles and generalized linear models. Since it is built on top of some low-level technologies such as Accelerate, BNNS, and Metal. Core ML is able to take advantage of the GPU and CPU for maximum efficiency and performance.
Core ML is also the foundation for frameworks that are domain specific and their functionality. It is effectively used for on-device performance, which is vital in minimising power consumption and memory footprint. Running on the device guarantees the overall privacy of the data of the user and ensures that your app will remain responsive and functional even when a network isn’t available.
Obtaining a Core ML Model
Get this model to be used in your app. It is important to note that Core ML supports various machine learning models, which include generalized linear models, tree ensembles, neural networks and support vector machines. Core ML needs the Core ML model format in order to be integrated into an app.
App offers different common open source models that are available in the Core ML model format. These models can just be downloaded and start integrating them into your apps. In addition, different universities and research groups are using their training data and models, which may not really be in the Core ML model format. It is important to convert them first before such models can be used.
With Core ML, Apple has actually made it extremely easy for many developers to get started with machine learning. Some of the incredible advantages of Core ML include:
- Comes equipped with a converter tool that supports a variety of training packages, such as Caffe, Kera, scikit-learn and more.)
- Core ML is not only for deep learning, but it also does decision trees, logistic regression and other machine learning models you can find
- This machine learning framework is also very easy and hassle-free to add into your app
There are obviously many different ways to perform machine learning on iOS, and Core ML is absolutely the main thing that you should try. If you find that your model isn’t supported by CORE ML, it’s always possible to get everything working with the use of the right tool.
Implementation:
Core ML requires few set of environment. One of which is Machine Learning Model.
Now we going to learn How to create Machine Learning Model and deploy it.
Now as our motive here is to show how to generate a model for given dataset.
if you like to learn from books by yourself try following:
For ML: Python Machine Learning by Example
Implementation:
Core ML requires few set of environment. One of which is Machine Learning Model.
Now we going to learn How to create Machine Learning Model and deploy it.
To create ML-model we going to use following data set.
R&D Spend
|
Administration
|
Marketing Spend
|
Profit
|
165349.2
|
136897.8
|
471784.1
|
192261.83
|
162597.7
|
151377.59
|
443898.53
|
191792.06
|
153441.51
|
101145.55
|
407934.54
|
191050.39
|
144372.41
|
118671.85
|
383199.62
|
182901.99
|
142107.34
|
91391.77
|
366168.42
|
166187.94
|
131876.9
|
99814.71
|
362861.36
|
156991.12
|
134615.46
|
147198.87
|
127716.82
|
156122.51
|
130298.13
|
145530.06
|
323876.68
|
155752.6
|
120542.52
|
148718.95
|
311613.29
|
152211.77
|
123334.88
|
108679.17
|
304981.62
|
149759.96
|
101913.08
|
110594.11
|
229160.95
|
146121.95
|
100671.96
|
91790.61
|
249744.55
|
144259.4
|
93863.75
|
127320.38
|
249839.44
|
141585.52
|
91992.39
|
135495.07
|
252664.93
|
134307.35
|
119943.24
|
156547.42
|
256512.92
|
132602.65
|
114523.61
|
122616.84
|
261776.23
|
129917.04
|
78013.11
|
121597.55
|
264346.06
|
126992.93
|
94657.16
|
145077.58
|
282574.31
|
125370.37
|
91749.16
|
114175.79
|
294919.57
|
124266.9
|
86419.7
|
153514.11
|
0
|
122776.86
|
76253.86
|
113867.3
|
298664.47
|
118474.03
|
78389.47
|
153773.43
|
299737.29
|
111313.02
|
73994.56
|
122782.75
|
303319.26
|
110352.25
|
67532.53
|
105751.03
|
304768.73
|
108733.99
|
77044.01
|
99281.34
|
140574.81
|
108552.04
|
64664.71
|
139553.16
|
137962.62
|
107404.34
|
75328.87
|
144135.98
|
134050.07
|
105733.54
|
72107.6
|
127864.55
|
353183.81
|
105008.31
|
66051.52
|
182645.56
|
118148.2
|
103282.38
|
65605.48
|
153032.06
|
107138.38
|
101004.64
|
61994.48
|
115641.28
|
91131.24
|
99937.59
|
61136.38
|
152701.92
|
88218.23
|
97483.56
|
63408.86
|
129219.61
|
46085.25
|
97427.84
|
55493.95
|
103057.49
|
214634.81
|
96778.92
|
46426.07
|
157693.92
|
210797.67
|
96712.8
|
46014.02
|
85047.44
|
205517.64
|
96479.51
|
28663.76
|
127056.21
|
201126.82
|
90708.19
|
44069.95
|
51283.14
|
197029.42
|
89949.14
|
20229.59
|
65947.93
|
185265.1
|
81229.06
|
38558.51
|
82982.09
|
174999.3
|
81005.76
|
28754.33
|
118546.05
|
172795.67
|
78239.91
|
27892.92
|
84710.77
|
164470.71
|
77798.83
|
23640.93
|
96189.63
|
148001.11
|
71498.49
|
15505.73
|
127382.3
|
35534.17
|
69758.98
|
22177.74
|
154806.14
|
28334.72
|
65200.33
|
1000.23
|
124153.04
|
1903.93
|
64926.08
|
1315.46
|
115816.21
|
297114.46
|
49490.75
|
0
|
135426.92
|
0
|
42559.73
|
542.05
|
51743.15
|
0
|
35673.41
|
0
|
116983.8
|
45173.06
|
14681.4
|
Now as our motive here is to show how to generate a model for given dataset.
The model we will develop will be in y = a1X1 + a2X2 + a3X3 ... + C form.
Now here y is a dependent variable which we will predict using X1, X2, X3... which we called labels.
here in above data lets say X1 is R&D spend, X2 is administration, X3 is Marketing spend and using this we gonna predict Y which is profit.
the basic motive is to draw a line(or parabola etc) in the coordinate system such that it all the label(X) and feature(Y) in the dataset remains close to or on the line.
To create the model with above data we are going to use Python 2.7 as core ml tools library doesn't have support for Python 3+.
Code To Create basic ML model Using sklearn:
#!/Users/prafulla/miniconda2/bin/python
# path for python
# give exc permission
# -*- coding: utf-8 -*-
#to read cvs exel etc
import pandas
dataset = pandas.read_csv('50_Startups.csv')
#Features : Are the variables in the row over which result is dependent
X = dataset.iloc[:,:-1].values
#Labels : this is what we going to predict for future data
y = dataset.iloc[:,3].values
#Encoding categorical data (As linear regression deals with number)
#anything string need to be change to numerical value if needed
#from sklearn.preprocessing import LabelEncoder,OneHotEncoder
#encode = LabelEncoder() # assign 0,1 value per label in row
#X[:,3] = encode.fit_transform(X[:,3])
#hotencode = OneHotEncoder(categorical_features=[3])
#X = hotencode.fit_transform(X).toarray()
# To avoid Dummy Variable trap
# This is automatically managed in Regression algorithm !!! (sci-kit)
#X = X[:,1:]// it handled in library automatically
# Training and Testing Set will enable me for two things:
# 1. Training set will help me to create a model. (70% dataset)
# 2. Testing set will help me evaluate my model for accuracy of prediction (30% dataset)
from sklearn.cross_validation import train_test_split
X_train,X_test,y_train,y_test = train_test_split(X,y,test_size = 0.3,
random_state=0)
# Fitting Multiple LR to training set
from sklearn.linear_model import LinearRegression
regressor = LinearRegression()
regressor.fit(X_train,y_train) #The output of this operation is a model
#Test the model for predictions based on test split
#y_pred = regressor.predict(X_test) # use this to check prediction i.e
# compare with actual result
# coefficients
regressor.intercept_
regressor.coef_
# now we will deploy above model
import coremltools
# convert to Core ML Model
coreml_model = coremltools.converters.sklearn.convert(regressor, input_features=["R&D Spend","Administration","Marketing Spend"], output_feature_names="Profit")
# deploy your model
coreml_model.save("ProfitPredictor.mlmodel")
#now this saved model we are going to use in our iOS App
#you can create various models with deferent algorithms and
#deploy it for you App
Now we are going to use "ProfitPredictor.mlmodel" in our small but ML enabled project.if you don't like to do all above stuff but wanted to learn only iOS UI part of it you can download models from here and try it in your projects.
Putting any ML Model file automatically generates its model class. All we have to do now is use that class.
The autogenerated code looks like following:
Putting any ML Model file automatically generates its model class. All we have to do now is use that class.
The autogenerated code looks like following:
//
// ProfitPredictor.swift
//
// This file was automatically generated and should not be edited.
//
import CoreML
/// Model Prediction Input Type
@available(macOS 10.13, iOS 11.0, tvOS 11.0, watchOS 4.0, *)
class ProfitPredictorInput : MLFeatureProvider {
/// R&D Spend as double value
var R_D_Spend: Double
/// Administration as double value
var Administration: Double
/// Marketing Spend as double value
var Marketing_Spend: Double
var featureNames: Set<String> {
get {
return ["R&D Spend", "Administration", "Marketing Spend"]
}
}
func featureValue(for featureName: String) -> MLFeatureValue? {
if (featureName == "R&D Spend") {
return MLFeatureValue(double: R_D_Spend)
}
if (featureName == "Administration") {
return MLFeatureValue(double: Administration)
}
if (featureName == "Marketing Spend") {
return MLFeatureValue(double: Marketing_Spend)
}
return nil
}
init(R_D_Spend: Double, Administration: Double, Marketing_Spend: Double) {
self.R_D_Spend = R_D_Spend
self.Administration = Administration
self.Marketing_Spend = Marketing_Spend
}
}
/// Model Prediction Output Type
@available(macOS 10.13, iOS 11.0, tvOS 11.0, watchOS 4.0, *)
class ProfitPredictorOutput : MLFeatureProvider {
/// Profit as double value
let Profit: Double
var featureNames: Set<String> {
get {
return ["Profit"]
}
}
func featureValue(for featureName: String) -> MLFeatureValue? {
if (featureName == "Profit") {
return MLFeatureValue(double: Profit)
}
return nil
}
init(Profit: Double) {
self.Profit = Profit
}
}
/// Class for model loading and prediction
@available(macOS 10.13, iOS 11.0, tvOS 11.0, watchOS 4.0, *)
class ProfitPredictor {
var model: MLModel
/**
Construct a model with explicit path to mlmodel file
- parameters:
- url: the file url of the model
- throws: an NSError object that describes the problem
*/
init(contentsOf url: URL) throws {
self.model = try MLModel(contentsOf: url)
}
/// Construct a model that automatically loads the model from the app's bundle
convenience init() {
let bundle = Bundle(for: ProfitPredictor.self)
let assetPath = bundle.url(forResource: "ProfitPredictor", withExtension:"mlmodelc")
try! self.init(contentsOf: assetPath!)
}
/**
Make a prediction using the structured interface
- parameters:
- input: the input to the prediction as ProfitPredictorInput
- throws: an NSError object that describes the problem
- returns: the result of the prediction as ProfitPredictorOutput
*/
func prediction(input: ProfitPredictorInput) throws -> ProfitPredictorOutput {
let outFeatures = try model.prediction(from: input)
let result = ProfitPredictorOutput(Profit: outFeatures.featureValue(for: "Profit")!.doubleValue)
return result
}
/**
Make a prediction using the convenience interface
- parameters:
- R&D Spend as double value
- Administration as double value
- Marketing Spend as double value
- throws: an NSError object that describes the problem
- returns: the result of the prediction as ProfitPredictorOutput
*/
func prediction(R_D_Spend: Double, Administration: Double, Marketing_Spend: Double) throws -> ProfitPredictorOutput {
let input_ = ProfitPredictorInput(R_D_Spend: R_D_Spend, Administration: Administration, Marketing_Spend: Marketing_Spend)
return try self.prediction(input: input_)
}
}
You don't have to worry about above code. All you need to know how we going to use it.
Now we are going to use above code to predict profit for any given data set. For that, I have created 3 text-views to take input for out models and on button click will display the output (complete project):
Now we are going to use above code to predict profit for any given data set. For that, I have created 3 text-views to take input for out models and on button click will display the output (complete project):
//
import UIKit
import CoreML
class ViewController: UIViewController {
var mlModel: ProfitPredictor?
@IBOutlet weak var profit: UILabel!
@IBOutlet weak var marketing: UITextField!
@IBOutlet weak var admin: UITextField!
@IBOutlet weak var rnd: UITextField!
override func viewDidLoad() {
super.viewDidLoad()
// init model
self.mlModel = ProfitPredictor.init()
profit.text = ""
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
@IBAction func predict(_ sender: Any) {
// fetch variable
guard let marketingInv = marketing.text else {
return
}
guard let adminInv = marketing.text else {
return
}
guard let rndInv = marketing.text else {
return
}
do {
// create indupt data model
let input = ProfitPredictorInput.init(R_D_Spend: Double(rndInv)!, Administration: Double(adminInv)!, Marketing_Spend: Double(marketingInv)!)
// give input data model to your mlmodel
let outData = try mlModel?.prediction(input: input)
// fetch output result Done
let result = outData?.Profit ?? 0
profit.text = "total Profit: \(result)"
} catch {
print("failed to get data")
}
}
}
Where to go from here?
you can grab python gist here and swift project here
What do we learn here:
you can grab python gist here and swift project here
What do we learn here:
- Creating basic ML Model using sklearn
- Deploy model for iOS project
- How to use model in iOS App
if you want to learn more about swift or iOS visit https://www.raywenderlich.com/ they have very tutorials.
if you want to learn more about machine learning visit https://www.coursera.org/learn/machine-learning
if you like to learn from books by yourself try following:


Comments
Post a Comment