[DL] CS231n Lecture 2 : Image classification pipeline
카테고리: DL
태그: DL
1. Image classification
Image Classification : Computer Vision(CV) 에서 가장 중요한 일은 이미지를 보고 이것은 고양이다 라고 판단하는 것
이것이 가능하면 Detection, Segmentation, Image captioning이 수월하게 가능해진다.
The problem : semantic gap
Challenges : viewpoint variation, illumination, Deformation, Occlusion, Background clutter, Intraclass variation
An image classifier
def predict(image):
# ?????
return class_label
이미지를 넣으면 그 이미지가 어떤 class에 속하는지 출력하는 함수
숫자를 정렬하는 알고리즘과는 다르게 고양이를 분류하는 명백한 알고리즘이 존재하지 않는다.
이것을 알아내려고 시도를 하긴 했음
지금 하려고 하는 것은 Data-driven approach
- 데이터 셋(images, labels)을 모은다
- 머신러닝을 사용해 image classifier를 학습시킨다.
- 테스트 이미지를 통해 classifier를 평가한다.
def train(train_images, train_labels):
# build a model for images -> labels....
return model
→ 이미지와 레이블을 받아 모델을 도출한다.
def predict(model, test_images):
# predict test_labels using the model...
return test_label
→ 만들어낸 모델과 테스트 이미지를 넣어 레이블을 반환한다.
Nearest Neighbor Classifier
Data-driven approach의 첫 번째 방법 : Nearest Neighbor Classifier (현재는 사용하지 않는 방식)
- 이미지와 레이블들을 메모리에 모두 기억(저장)
- 예측단계에서는 모든 이미지와 비교해서 그 중에 가장 비슷한 것을 반환
테스트 이미지를 모든 Training Set과 비교를 한다고 했는데 어떻게 비교하는 걸까?
⇒ distance metric
L1 distance = Manhattan distance 라고도 불림
Nearest Neighbor Classifier Code
import numpy as np
class NearestNeighbor:
def __init__(self):
pass
def train(self, X, y):
""" X is N x D where each row is an example. Y is 1-demension of size N """
# the nearest neighbor classifier simply remembers all the training data
self.Xtr = X
self.ytr = y
# X는 이미지, 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
Yperd = np.zeros(num_test, dtype = self.ytr.dtype)
# loop over all the rows
for i in xrange(num_test):
# find the nearest training image to the i'th test image
# using the L1 distance (sum of absolute value difference)
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
Q : how does the classification speed depend on the size of the training data?
A : linearly 하게 증가 Training dataset 2배 증가 → 시간 2배 증가
⇒ 단점
각 상황에 맞게 L1 일지 L2일지 해봐야 안다 → Hyperparameter
A : 이미 Training data를 기억하고 있기 때문에 distance가 0이므로 정확도 100%
지금까지 정리를 해보자면
What is the best distance to use? ⇒ L1을 써야할 까 L2를 써야할까
What is the best value of k to use? ⇒ K-NN이라면 K에 5를 써야할까 10을 써야할까
우리는 이런 것을 hyperparameters로 알고있는데, 어떻게 설정해야할까
문제에 따라 다르다, 주어진 환경에서 각각의 하이퍼파라미터를 실험해보고 가장 결과가 좋은걸 선택
Test data를 사용하는 것은 절대 절대 안됨..! 최후의 보루로 남겨둬야한다.
그래서 등장한 Validation data 20%정도를 떼어내어 사용한다.
fold 1 ~ 4에서 training → fold 5 Validation
fold 1 ~ 3, 5에서 training → fold 4 Validation 를 5번 반복
하이퍼파라미터인 K가 7일 때 가장 좋아서 K를 7로 설정한다
K-NN은 현실에서 사용하면 안된다.
- 시간이 너무 오래걸린다.
- 정확한 예측이 어렵다
4. Linear Classification
4.1 Image captioning
CNN으로 Classification
RNN으로 문장을 구성
x : image, W : parameter
이미지 (32x32x3 = 3072)를 single column 으로 쫙 핀다 ⇒ 3072 x 1
우리는 결과를 10개의 숫자로 받아야 하므로 W ⇒ 10 x 3072
그러므로 우리가 Control 해야 하는 것은 총 30720개의 Weights 이다.
Q1. Linear Classifier 이란?
- 모든 이미지의 픽셀값들에 대해 가중치를 곱하여서 처리를 하는 것의 합이다.
- → Just a weighted sum of all the pixel values in the image
- 각각 다른 공간적 위치에 있는 컬러들을 카운팅 하는 것이다.
- → Counting colors at different spatial position
Car : Train data에 빨간색 자동차가 많았을 것이다.
Horse : 왼쪽, 오른쪽을 보고 있는 말들이 흐릿하게 중첩
⇒ 만약 노란색 자동차가 들어온다면 Frog로 식별할 가능성이 높다
Q2. linear classifier가 구분하기 어려운 것은?
- negative flim 같은 색상이 반전되는 경우
- gray 색상의 이미지 → 텍스쳐나 디테일을 봐야됨
- 색상이나 텍스처가 다른데 형태는 동일한 경우
지금까지 한 것은 Linear classifier의 Score function을 계산한 것
이제 해야할 것은 Loss function을 알아야 한다. 우리가 계산한 Score가 얼마나 좋고 나쁜지를 판단
5. Summary
- Image Classification : 레이블된 이미지의 Training Set을 받고, Test Set의 레이블을 예측
- K-Nearest Neighbor Classifier : Training set에서 가장 가까운 이미지 선택 (거리 기준)
- 하이퍼 파라미터인 Distance(L1, L2)와 K를 설정할 때는 Validation Set을 사용한다.
- 데이터 셋이 작다면 Cross-validation
- 최적의 하이퍼 파라미터가 선택됐다면, Classfier는 테스트 셋을 평가하고 그것을 kNN의 성능이라고 해야함.
댓글남기기