簡單CoreML 學習碎碎念
https://developer.apple.com/machine-learning/
前幾天看了一個ML的課程跟著做了一個app, 做完發現我不懂這怎麼運作因此還做了惡夢 , 今天就就來看一下 ML,
這是寫之前App的小筆記:
1.Download model SqueezeNet。(model : 推測圖片所在的情境地點,例如 衣帽商店 洗衣店 )
2.Drag it to project : 3 checked : copy item , make group , to target
3.coding :
//Set up Module
//Create a vision request
//create CI image
//run the google modle classifier : create handler and perform request
model 沒有放在正確target 時出現錯誤訊息 :
“Model is not part of any target. Add the model to a target to enable generation of the model class.”
在專案的 Build Phases/Compile Source 中加入該 .mlmodel
或 在.mlmodel 的 file inspector 中, target membership 勾選使用 . 可以觀察 Model Classes 處會顯示出swift 的interface (Automatically generated Swift model class)
從官網最一開始看到三個重點是:
- (overview)You can run machine learning models on the device so data doesn't need to leave the device to be analyzed.
->在自己的裝置上運行ML model, 這樣資料就不用送出本身的裝置
(vision) 目前支援的影像處理有 臉部追蹤 臉部偵測 文字偵測 地標偵測 方型偵測 物件追蹤 barcode , 圖形註冊(image register )
(nature language processing : NLP) 透過 tokenization language identification ...等text相關
接下來來看文件 https://developer.apple.com/documentation/coreml
簡介CoreML
資料來源 : 官網教學簡報
Machine Learning 有兩個重點, 一是traning , 二是推斷(inference)
traning 是在offline 時將大量圖片及資料(例如給他一堆照片告訴他是什麼花)餵去學習演算法(learning algorithm)後產生model ; 而後來的標的物(img)再經過model 推斷(inference)出我們要的結果, 例如一張花的照片透過model 推斷後給出資訊是有 87%準確率是玫瑰花. 而這其中的挑戰是 correct, performance 以及energy efficiency.
ML framework :
寫app首先可以使用這兩種framework: vision(處理電腦視覺相關) 或 NLP(自然語言處理, text-based),或 GameplayKit (evaluating learned decision tree) ;沒有理想格式就往下使用CoreML ; 在不足就往下使用accelerate 與 MPS(Metal performance Shaders) 來做客製化的Model ;
Model as Code把Model 拉到 Xcode中時 XCode 會自動產生一個Swift檔的interface ,供App使用 ; 而compile 時也會把 Model compile 並 bundle 到app中
Integrating a Core ML Model into Your App
簡單sample 的步驟 :
- adding a model to xcode project : 將model拖曳到專案內, 並且確認有勾選 to target 正確位置; 進入專案後點選該. mlmodel 可以看到model class 是系統幫你產生的swift 檔 interface , 而model evaluation parameters 是 input output
- creating the model in code :
let model = MarsHabitatPricer()
Getting Input Values to Pass to the Model:整理待推測的input數據
use the model to make predictions :
guard let marsHabitatPricerOutput = try? model.prediction(solarPanels: solarPanels, greenhouses: greenhouses, size: size)
Classifying Images with Vision and Core ML
sample 使用了官方提供的mobileNet model ,可以根據圖片推斷是什麼物件
會使用VNCoreMLModel 處理visionRequest
摘要步驟:
- set up vision request with a CoreML model
let model = try VNCoreMLModel(for: MobileNet().model)
let request = VNCoreMLRequest(model: model,completionHandler: {[weak self]request,error in
self?.processClassifications(for: request,error: error)})
request.imageCropAndScaleOption = .centerCrop
return request
create 一個(model) class 的instance ,用他的model property 去產生 VNCoreMLRequest
object , 再用 request object 的 completion handler to specify a method to receive results from the model after you run the request.