Core ML and Vision Framework on iOS 11

莉森羊
6 min readMar 21, 2018

--

大約是 2018/01 小玩這個,在這邊做一個整理,本篇文章主要介紹:

Part A. 如何使用 Core ML and Vision :圖像識別例子

Part B. 如何使用自訓練的模型,轉換成Core ML模型:MNIST手寫辨識例子

環境需求

Xcode 9 Beta 1 or later, Swift 4 and iOS 11.

Core ML & Vision 是什麼?

Core ML 是 Apple 在 WWDC 2017 推出的機器學習框架

可以把Core ML看成一個模型的轉換器,它可將一個 ML Model 格式的模型文件自動生成 class 和方法,讓我們能夠方便在app中使用訓練好的模型。

Vision 是 Apple 在 WWDC 2017 推出的圖像識別框架

Vision 本身包含人臉檢測識別、機器學習圖片分析、條形碼檢測、文本檢測等功能。另外,Vision也能使用一個你設置好的其它Core ML Model來對圖進行分析。

Part A: 用CoreML的預訓練模型進行圖像識別

將 Core ML 模型集成到 App

  1. 模型下載位址:https://developer.apple.com/machine-learning/
  • 這邊選pretrained model: Inception v3 ,為深度學習之圖像分類,可區分1000多類的圖像。

2. 下載 Inceptionv3.mlmodel 後,放到 Resources 下 :

  • 此時可查看Xcode 已生成了 input 和 output 類別以及主類別 Inceptionv3,主類別有一個 model 屬性和兩個 prediction 方法。
  • Vision 框架會將圖片轉成正確的 input 類型,也會將 Inceptionv3Output 屬性轉換為自己的results類型,並管理 prediction 方法的調用。

3. swift撰寫:包含UI介面,點選功能等(這邊不做詳述)

4. demo如左圖

在 Vision Model 中包裝 Core ML Model

Part B: 用自訓練的MNIST模型進行圖像識別

除了利用Apple提供的模型之外,也可使用自己訓練過的模型,前提是需使用受支持的機器學習工具訓練的,例如 Caffe、Keras 或 scikit-learn,Converting Trained Models to Core ML 介绍了如何將其轉換為 Core ML 格式。

  1. 以MNIST手寫辨識為例,首先先用Keras訓練Convolutional Neural Networks Model

2. Keras to CoreML

  • 環境安裝

Note: 目前要在python 2.7的環境才可以轉模型…

conda create -n coreml python=2.7
source activate coreml
# 轉到環境(coreml),安裝所需套件 conda install pandas matplotlib jupyter notebook scipy scikit-learn opencv
pip install tensorflow==1.1
pip install keras==2.0.4
pip install h5py
pip install coremltools
  • 將Keras模型轉換成CoreML

透過coremltools套件,將自訓練的Keras Model 轉成 mnistCNN.mlmodel 格式,就可以照 Part A方式,在app上使用該模型進行分析應用囉~

import coremltoolsoutput_labels = ['0', '1', '2', '3', '4', '5', '6', '7', '8', '9']scale = 1/255.coreml_model = coremltools.converters.keras.convert('./mnistCNN.h5',input_names='image',image_input_names='image',output_names='output',class_labels=output_labels,image_scale=scale)coreml_model.author = 'Sri Raghu Malireddi'coreml_model.license = 'MIT'coreml_model.short_description = 'Model to classify hand written digit'coreml_model.input_description['image'] = 'Grayscale image of hand written digit'coreml_model.output_description['output'] = 'Predicted digit'coreml_model.save('mnistCNN.mlmodel')
  • demo

題外話,想研究的技術很多,但時間過得毫不留情呀!(最後動畫倒是看得不少…XD)

--

--

No responses yet