Created
October 7, 2020 10:57
-
-
Save choiseoungho/df090d6cd9e6ca6bffd7bcae0eab8dd3 to your computer and use it in GitHub Desktop.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
@import TFLTensorFlowLite; | |
iOS기기에서 TensorFlowLite 로 .tflite 모델을 사용할 수 있음. | |
TensorFlow Lite를 바로 사용할 시 C++ 인터페이스 | |
TensorlFlow Mobile 의 다음 버전 | |
더 작은 바이너리 | |
적은 의존성, 더 나은 퍼포먼스 | |
iOS 기기에서 CoreML로 .mlmodel 모델을 사용할 수 있음. | |
텐서플로우 .pb를 CoreML로 변환하여 사용. | |
Tensorflow + swift | |
18년 5월 처음 공개 | |
Firebase | |
모바일 앱을 만드는데 필요한 여러 가지 기능을 갖추고 있는 클라우드 서비스입니다. | |
Core ML model -> Core ML -> Your App | |
Image access | |
ARKit -> Simple to set up and usable with Augmented Reality. | |
AVFoundation -> real time | |
UIImagePicker - Allows a user to choose a photo from their photo library. | |
Create your own Object Recognizer - ML on iOS | |
https://medium.com/@hunter.ley.ward/create-your-own-object-recognizer-ml-on-ios-7f8c09b461a1 | |
Create your own object recognizer | |
- Training , Model Conversion | |
- Real Time Computer Vision on mobile | |
Technologies | |
-iOS 11, Core ML, Xcode, Swift 4.0, ARKit | |
Five Step Process | |
CoreML model -> using Microsoftt Azure Congnitive Service | |
https://www.customvision.ai/ | |
https://github.com/hanleyweng/Gesture-Recognition-101-CoreML-ARKit | |
Custom Vision do the hard work | |
- Upload Images | |
- Train | |
- Evaluate | |
Train your Data | |
Precision and recall result | |
Export the model | |
Renaming the .mlmodel file before importing it into Xcode. | |
Load and run the Core ML model in your app | |
Real time alongside ARKIt. | |
Create an Account | |
Create a New Project with the Domain “General(compact)” | |
참조 | |
https://kka7.tistory.com/106 | |
VNCoreMLRequest API 와 NLModel API를 사용하여 앱의 ML 기능을 크게 향상 | |
모델 크기, 모델의 성능, 모델의 사용자 정의 | |
애플은 개발자들에게 CoreML모델을 양자화 하는 도구를 제공하기로 결정 | |
모델을 양자화 하는 것은 더 작은 형식으로 숫자를 저장하고 계산하는데 사용하는 기술. | |
숫자를 줄이거나 공간을 덜 차지하는 형식으로 저장하는 경우에 모델의 크기를 획기적으로 줄일 수 잇다. 이로 인해 실시간 메모리 사용량이 줄어들고 계산이빨라진다. | |
머신 러닝 모델의 핵심 3가지 | |
- 모델의 숫자 (The number of models) | |
- 가중치의 숫자 (The number of weights) | |
- 가중츼의 크기 (The size of the weights) | |
####코드 | |
from coremltools.models.neural_network.quantization_utils import * | |
model = coremltools.models.MLModel(“./Inceptionv3.mlmodel”) | |
-> linear quantization | |
lin_quant_model = quantize_weights(model, 16, "linear") | |
lin_quant_model.save(“./QuantizedInceptionv3.mlmodel”) | |
—> Kmeans quantization | |
lut_quant_model = quantize_weights(model, 16, "kmeans") | |
lut_quant_model.save(“./QuantizedlutInceptionv3.mlmodel”) | |
Test | |
compare_models(model, lin_quant_model, '/Users/SaiKambampati/Desktop/SampleImages') | |
Performance | |
-> Classification / Style Transfer) | |
이 알고리즘에 대한 특정 입력을 설정합니다. 신경망 내의 각 레이어는 원본 이미지에 특정 변형을 추가합니다. 이는 모델이 모든(every) 입력을 받아 출력물에 매핑하여 예측해야하는 것을 의미합니다. 예측(prediction)은 가중치(weights)를 만드는데 도움이 됩니다. 코드는 어떻게 될까요? | |
//Loop over inputs | |
For I in 0..< modelInputs.count{ | |
modelOutputs[I] = model.prediction(from: modelInputs[I], options: options) | |
} | |
위의 코듵에서 보면, 각 입력에 대해 모델에 예측을 만들고자 몇가지 옵션(options)을 기반으로 출력을 만들어 냅니다. 오랜 시간이 걸리므로 | |
이를 해결하기 우해, 애플은 새로운 Batch API를 도입. | |
For 반복문과 다르게, 머신러닝 안의 배치는 모델의 모든 입력이 공급될때 이고 정확한 예측이 그 결과가 된다. 이는 훨씬 더 적은 시간이 걸릴 수 있고 더 적은 코드가 됨. | |
ModelOutpus = model.prediction(from: modelInputs, options:options) | |
guard let prediction = try? model.prediction(image: pixelBuffer!) else { | |
return | |
} | |
classifier.text = "I think this is a \(prediction.classLabel)." | |
iOS 11에서 Core ML 모델은 32 비트모델로 저장. | |
iOS12에서, 애플은 모델을 16비트와 8비트 모델로 저장할 수 잇는 기능을 주었다. | |
가중치(weights)에 대해서 익숙하지 않는 경우에, 좋은 예가 있습니다. 집에서 슈퍼마켓으로 간다고 합시다. 제일먼저, 어떤길로 갈것인지 선택할수 있습니다. 두번째, 이미 마켓으로 가는방법을 알고 있기 때문에,슈퍼마켓으로 가는 가장 짧은 길을 찾으려고 할것입니다. 세번째로, 이전의 2개의 경로를 알고 있기 때문에, 더 짧은 경로를 선택할 것입니다. 마켓에 갈때마다, 시간이 지날수록 더 짧은 길을 선택하는 것을 배우게(learn)될 것입니다. 어떤 경로를 선택해야 하는지 아는 것을 가중치(weights)라고 합니다. 따라서(Hence), 가장 정확한 경로는, 가중치(weights)가 가장 큰 것입니다. | |
데모를 위해 Inceptionv3을 이용해서 | |
양자화(quantize)하기 위해서 파이썬 패키지 (coremltools)를 사용할 것 | |
하지만 신경망을 Tensorlflow 에서 | |
iOS 12 에서 애플 엔지니어는 Swift에서 자신만의 레이어를 만들 숭 ㅣㅆ는 MLCustomLaeyr 프로토콜를 도입. | |
MLCustomLayer으로, CoreML 모델에서 자신만의 신경망 레이어들의 동작을 정의할 수 있다. 하지만 사용자 정의 레이어는 신경망 모델에서만 동작한다는 것을 주목. | |
CoreML3 을 통해 mlmodel 을 받아서 | |
-> 있는 모델 돌려 보기. Resnet50, MobileNetV2, SqueezeNet | |
-> DeeplabV3, YOLOV3, YOLOV3-Tiny | |
Create ML로 모델 학습시키기 | |
-> Create ML앱을 사용하면 모델을 구축하고 학습시키고 배포할 수 있다. | |
eGPU 학습 지원 | |
Mac 에서 외장 그래픽 처리 장치를 사용하여 모델 학습을 위한 성능을 개선 | |
- 애플에 최적화 상태로 올리기 위해서는 애플에서 제공하는 MacPro을 이용해서 학습해야됨. | |
Core ML3 의 새로운 기능 | |
CoreML Converter | |
https://github.com/tf-coreml/tf-coreml | |
애플에서 제공해주는 자기만의 모델 만드는 것. | |
https://github.com/apple/turicreate | |
Xcode 11.1 GM seed | |
다운 | |
CoreML 데모 만드는 것 (**) | |
[0] http://throughkim.kr/2017/09/06/ios-coreml/ | |
[1] https://www.appcoda.com/coreml-introduction/ | |
[2 ]https://www.raywenderlich.com/577-core-ml-and-vision-machine-learning-in-ios-11-tutorial | |
기본 프로젝트는 이미 사진첩에서 이미지를 가져와 인터페이스에 표시해주는 기능을 갖고 있다. | |
CoreML 모델을 앱과 통합하기 | |
- 만약 Caffe,Keras 등을 이용해 생성된 모델을 사용하고 싶은 경우, Converting Trained Models to Core M | |
CoreML 모델을 Vision Model 로 래핑하기 | |
VNCoreMLModel은 Vision 요청에 CoreML을 사용할 수 있도록 해주는 컨테이너 | |
Vision의 표준 워크플로우는 모델을 생성하고, 하나 이상의 요청을 생성한 뒤, 요청 핸들러를 생성 및 실행시키는 방식으로 진행 | |
IBActionsextraion 이래에 다음 extension을 추가 | |
// MARK: - Methods | |
extension ViewController { | |
func detectScene(image: CIImage) { | |
answerLabel.text = "detecting scene..." | |
// Load the ML model through its generated class | |
guard let model = try? VNCoreMLModel(for: GoogLeNetPlaces().model) else { | |
fatalError("can't load Places ML model") | |
} | |
} | |
} | |
detectScene(image) 의 마지막 라인에 추가 | |
// Create a Vision request with completion handler | |
let request = VNCoreMLRequest(model: model) { [weak self] request, error in | |
guard let results = request.results as? [VNClassificationObservation], | |
let topResult = results.first else { | |
fatalError("unexpected result type from VNCoreMLRequest") | |
} | |
// Update UI on main queue | |
let article = (self?.vowels.contains(topResult.identifier.first!))! ? "an" : "a" | |
DispatchQueue.main.async { [weak self] in | |
self?.answerLabel.text = "\(Int(topResult.confidence * 100))% it's \(article) \(topResult.identifier)" | |
} | |
} | |
요청 핸들러 생성 및 실행 detectScene(image)의 마지막 라인에 추가 | |
// Run the Core ML GoogLeNetPlaces classifier on global dispatch queue | |
let handler = VNImageRequestHandler(ciImage: image) | |
DispatchQueue.global(qos: .userInteractive).async { | |
do { | |
try handler.perform([request]) | |
} catch { | |
print(error) | |
} | |
} | |
-> VNImageRequsetHandler는 VIsion 프레임워크의 표준 요청 핸들러 | |
detectScene(Image:)에서 전달 받은 이미지를 입력받은 뒤 perform 메소드를 호출하여 요청 배열을 전달 후 핸들러를 실행 | |
이미지 분석을 위해 모델 사용하기 | |
detectScence (Image:)메소드를 두 장소에서 호출해주기만 하면 된다. 다음 라인을 viewDidLoad()의 마지막 줄 그리고 imagePickerController(_:didFinishPickingMediaWithinfo:)의 마지막 줄에 추가. | |
guard let ciImage = CIImage(image: image) else { | |
fatalError("couldn't convert UIImage to CIImage") | |
} | |
detectScene(image: ciImage) | |
사진첩에서 다른 사진을 불러와서도 확인해볼 수 있다. | |
How to Deploy a TensorFlow Lite model to iOS | |
https://medium.com/datadriveninvestor/how-to-deploy-a-tensorflow-lite-model-to-ios-4b230bb91ac0 | |
Storyboard 에서동그라미에 네모가 아이콘 입력 |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment