[CS231n] Lecture-2-Image-Classification
2강 Video 바로가기

  • Contents
    • The data-driven approach
    • K-nearest neighbor
    • Linear classification I

Image Classification: The data-driven approach

지난번에 말했던 이미지 분류에 대해서 말해보려 한다. dog, cat, truck, plane으로 fixed categories labeled 작업의 이미지 분류에 대해서이다.

image

이미지 인식은 사람에게는 쉬운 일이지만 컴퓨터에게는 굉장히 어려운 일이다. 컴퓨터는 단순히 RGB의0 3개의 layer에 0~255 사이의 숫자로 인식하기 때문에 사람이 인식하는 것과는 의미적 차이(Semantic gap)가 존재한다. Viewpoint variation(각도), Illumination(조명), deformation(자세), occlusion(가려짐), Background Clutter(배경과의 비슷함), Intraclass variation(종의 다양함) 등의 문제를 사람은 쉽게 구분하지만 컴퓨터에게는 어렵다.

이미지 분류는 어떻게 할 것인가?

image

만약 ‘고양이를 분류하는 알고리즘’을 만든다면, 예전처럼 이미지의 Edge를 찾고, 그 코너를 찾고, 고양이라면 뾰족한 귀가 두 개 있다는 이러한 명시적인 규칙을 찾아서 알고리즘을 만들 수 있다. 그러나 이것은 해보지 않아도 당연히 현실에 잘 작동하지 않을 것이다.

image

Data-Driven Approach는 많고 다양한 class의 이미지 데이터를 label과 함께 학습해서 각각의 class의 시각적 모습을 학습하여 알고리즘을 만드는 것이다. 따라서 명시적인 규칙(혹은 hard-code algorithm)이 있는게 아니라 주어진 training dataset을 따로 학습하는 train과 이미지를 예측하는 predict의 알고리즘으로 나누어서 만든다.


K-Nearest Neighbor classifier

그 Data-driven approach의 한 기법이 K-Nearest Neighbor Classifier이다. 주어진 데이터를 학습해서 분류하는 모형을 만든다.

import numpy as np

class NearestNeighbor(object):
  def __init__(self):
    pass

  def train(self, X, y):
    """ X is N x D where each row is an example. Y is 1-dimension of size N """
    # the nearest neighbor classifier simply remembers all the training data
    self.Xtr = X
    self.ytr = y

  def predict(self, X):
    """ X is N x D where each row is an example we wish to predict label for """
    num_test = X.shape[0]
    # lets make sure that the output type matches the input type
    Ypred = np.zeros(num_test, dtype = self.ytr.dtype)

    # loop over all test rows
    for i in range(num_test):
      # find the nearest training image to the i'th test image
      # using the L1 distance (sum of absolute value differences)
      distances = np.sum(np.abs(self.Xtr - X[i,:]), axis = 1)
      min_index = np.argmin(distances) # get the index with smallest distance
      Ypred[i] = self.ytr[min_index] # predict the label of the nearest example

    return Ypred

image

위처럼 K와 distance metric(L1, L2)에 따라 training이 달라진다.

image

image

여기서 K와 distance metric은 Hyperparameter라고 한다. data에 존재하는 parameter가 아니라 data를 떠나 문제 의존적인 결정사항이다. 이때 Hyperparameter는 data를 train, validation, test로 나눈 다음에 train data로 훈련한 hyperparameter를 validation data으로 평가해서 고르고, 그것을 test data로 평가한다. K-fold validation을 사용할 수 도 있다. (그러나 K-fold validation은 deep learning에서는 자주 사용하지 않는다.)

image

그러나 knn은 이미지 분류에 잘 안쓴다. 왜냐하면 test time이 오래걸리고, distance metric이 informative하지 않고, 또한 class가 늘어날 수록 차원의 저주가 생기기 때문이다.


Linear classification

Linear classification은 아주 단순하지만 CNN에 매우 중요하다!

image

Linear classifier을 레고 불록에 비유할 수 있다. 이 레고 블록 하나하나가 linear classifier인 것이고 이것이 모여서 큰 Neural Network가 되는 것이다.

image

선형분류는 가장 단순한 모수적 모델(Parametirc model)이다. Knn은 모수가 필요하지 않았다. 그러나 선형분류는 train을 통해 W를 가지면 test에 W만으로 피팅할 수 있다. b는 bias term인데 만약 unbalanced data라서 만약 cat이 dog보다 많다면 cat의 카테고리에 해당하는 bias term이 클 것이다

image

이미지 class에 대한 학습된 Weights를 보면(train 후 역으로 구한 이미지) 그 class의 이미지와 비슷하게 생겼다. 그러나 선형이기 때문에 좌우 대칭이다. (horse를 보면 잘 드러난다.)

image

Linear classifier의 문제점으로, Odd even 구분, Multimodal case, 그리고 흩어진 공간에 존재하는 경우는 선형으로 구분하지 못한다는 문제가 있다. 그럼에도 불구하고 Linear Classifier는 아주 간단하고 이해하고 해석하기 쉽다는 장점이 파워풀하다.

image

지금까지 linear score fucntion을 알아보았다. 그렇다면 과연 학습한 Weights가 좋은지 나쁜지는 어떻게 구분할 수 있을까?

image

다음 시간에는 좋은 Weight란 어떻게 정량화하는가에 대한 Loss Function, 그리고 그 loss를 줄여주는 Optimazation, 함수 형태를 조절하는 CovNet에 대해서 배워볼 것이다.