쑤쑤_CS 기록장

Chapter2 : Getting Started with Image Classification 본문

IT 지식 기록/ML for iOS | 인공지능

Chapter2 : Getting Started with Image Classification

(╹◡╹)_ 2020. 7. 13. 16:33
728x90

* classifier란?

A classifier is a machine learning model that takes an input of some kind, in this case an image, and determines what sort of “thing” that input represents. 

Image clssifier는 어떤 카테고리, 클래스에 이미지가 속하는지를 알려준다.

* Binary란?
classifier가 objects를 두 개의 클래스로 구분한다.
예를 들어 사진 -> Binary Image Classifiet - > cat / dog 이렇게

이미지를 cat이나 dog로 분류를 진행한다.

단지 두가지로 분류하는게 의미없어 보일 수 있지만 다양한 분야에서 사용된다.
의학계의 경우 환자가 질병이 있는지 없는지를 negative와 positive로 판단하고,
스팸 메일의 경우 해당 메일이 스팸인지 / 아닌지 로 판단하는 등의 예시가 있다.

이렇게 machine learning의 binary classifier는 질문에 대한 답을 yes / no 로 

특정 클래스에 속하는지 / 아닌지의 답을 알려준다.

Image classification은 computer vision tasks의 가장 기본적인 작업 중의 하나이다.
Image classifier에는 다양한 방법이 있지만, 그중에서 가장 좋은 결과를 내는 것은 딥러닝 이라고 수 있다.


< Is that snack healthy? >

이번 단원에서는 snacks의 healthy 와 unhealthy를 알려줄 수 있는 image classifier에 대해 다루려고 한다.

HealthySnacks 라는 이름의 Xcode를 실행한다.

사진을 select하면 app은 ViewController.swift를 통해 이미지가 healthy snack인지 아닌지를 판단한다.

Machine learning을 진행하기 위해서는 model을 train 해야한다.

 

해당 문제에서는 how to tell apart healthy snacks form unhealthy snacks를 알 수 있어야한다.

2단원에서는 이미 만들어진 모델을 사용하려 한다.

 

모델은 아래와 같이 train이 진행되었다.

모델은 사실 healthy와 unhealthy 만을 판단하는것이 아니라 probability distribution의 결과는 나타낸다. healthy에 대한 확률과 unhealthy에 대한 확률을 결과값으로 나타낸다. [0.15, 0.85]와 같이 총 합이 1이 되도록 각 클래스에 대한 확률이 나타난다.

 

The more confident the model is about its prediction, the more one of the probabilities goes to 100% and the other goes to 0%. When the difference between them is large, as in this example, it means that the model is sure about its prediction.

 

 

* Core Ml

은 머신 러닝을 앱에 더하기 쉽게 만들어주는 애플의 머신러닝 프레임워크이다.

 

.mlmodel 파일에 들어있다. 이 파일에는 모델의 구조적 정의와 학습된 매개변수 모델이 포함되어 있다.

 

HealthySnacks model type은 Neural Network Classifier이고 이는 딥러닝 기술을 이용한 이미지 classifier 이다. 

 

모바일 앱에서 너무 크기가 큰 모델은 적합하지 않다.

 

.mlmodel file을 project에 넣으면 Xcode가 알아서 앱에서 모델을 사용하기 위한 Swift class를 생성한다. 사용자가 추가적으로 .mlmodel을 load하기 위한 코드를 작성할 필요 없다는 것이다.

 

At this point, you might reasonably expect that you’re going to use these automatically generated classes to make the predictions. Surprise... you’re not! We’re saving that for the end of the chapter.

There are a few reasons for this, most importantly that the images need to be scaled to 227×227 pixels and placed into a CVPixelBuffer object before you can call the prediction method, and we’d rather not deal with that if we can avoid it. So instead, you’re going to be using yet another framework: Vision.

 

 

* Vision

은 컴퓨터가 vision tasks 하는 것을 돕는다.

 

 

Vision makes it easy to run Core ML models that take images as input. You can even combine this with other Vision tasks into an efficient image-processing pipeline. It’s highly recommended that you use Vision to drive Core ML if you’re working with images.

 

Finally, Vision also performs a few other tricks, such as rotating the image so that it’s always right-size up, and matching the image’s color to the device’s color space. Without the Vision framework, you’d have to write a lot of additional code! 

 

 

* Creating the VNCoreML request

 

프로젝트에 실제 코드를 작성해본다. ViewController.swift에 작성한다.

 

* 오류를 겪었던 부분

- .mlmodel의 위치가 프로젝트에 적합하지 않게 위치해있으면 모델을 인식하지 못한다. 정확한 위치는 다음과 같다.

이때 위치를 바꾸거나 파일을 삭제하는 것이 어려우면, 오른쪽 마우스 클릭 후 'Finder 에서 보기'를 진행하면 된다.

 

* Crop and scale options

 

Vision이 자동적으로 올바른 사이즈로 scale 해줄것이다.

Resize 뿐만 아니라 모델에 올바른 방법을 선택하여 제대로 작동하는 것도 필요하다. 이때 correct method란 모델이 어떻게 trained 되었는지에 따른다. 사용된 이미지는 다른 dimensions, aspect ratios, pixels size를 가진다. vision은 centerCrop, scaleFill, scaleFit의 possible choices를 offer한다.

 

 

* Image orientation

ios는 이미지에 대해 imageOrientation property를 가진다.

0 degrees란 사진이 landscape withe the Home button on the right를 의미한다.
(핸드폰의 홈 버튼이 오른쪽에 있는 상태를 의미하므로, 가로 방향으로 길게 그리고 홈버튼이 오른손 엄지손가락에 오는 방향이 0도를 의미한다.)


그리고 시계방향으로 각도가 증가한다.
즉, 우리가 핸드폰을 주로 바라보는 세로, 똑바로 세워진 방향의 경우 이는 0 + 90인 90도 이다.

CoreML model은 image orientation 정보를 input 값으로 가지지 않으니, raw pixels 정보만 확인할 것이다. 

대부분의 image classifiers는 90, 180, 270 도로 회전된 이미지들에 대해서 trained 되어있지 않다. 

제대로 방향이 맞춰지지 않은 이미지를 모델에 넣으면 정확한 예측을 할 수 없다.

따라서 Vision을 통해서 올바른 방향으로 이미지 픽셀이 모델을 통과하기 전에 들어가는 것이 필요하다.  

you need to convert the UIImage.Orientation value to a CGImagePropertyOrientation value.

* Into the next dimension

Decision boundary라 불리는 선이다. Classifier model이 decision boundary 가 어디인지 learn할 수 있게 한다. 

Neural network가 healthy snack와 unhealthy snack을 분리하는데 사용된다.

 

* A concrete example

* Multi-class classification

Binary classification에서는 2개의 클래스로반 분리를 한다. 

그러나 multi-class classification에서는 여러개의 클래스를 다룬다. MultiSnacks.mlmodel 모델을 사용하면 된다. 

 



* Key points

1. Obtain a trained .mlmodel file from somewhere. You can sometimes find pre- trained models on the web (Apple has a few on its website) but usually you’ll have to build your own. You’ll learn how to do this in the next chapter.

2. Add the .mlmodel file to your Xcode project.

3. Create the VNCoreMLRequest object (just once) and give it a completion handler that looks at the VNClassificationObservation objects describing the results.

4. For every image that you want to classify, create a new VNImageRequestHandler
object and tell it to perform the VNCoreMLRequest.

 

 

 

단어 정리

Confidence 자신. 신임. 신용

Recap 요점을 되풀이하다

728x90
Comments