본문 바로가기
카테고리 없음

[CS231n] 3. Loss Functions and Optimization

by sk_victoria 2021. 4. 25.

출처 : www.youtube.com/watch?v=h7iBpEHGVNc&list=PLC1qU-LWwrF64f4QKQT-Vg5Wr4qEE1Zxk&index=3


< Last Time Recall >
- Recognition Difficulty
- Data-driven approach
- Image Classification
  - why is it hard? -> illumination, deformation, semantic gap, Computer Vision vs. Human Eyes
- use KNN to make decision boundaries
- Linear Classification (parametic classifier)
  > score function s = f(x;W) = W*x
  > each rows of W : class의 template으로써 기능 ( How much does this pixel influence that class? )
  > linear decision boundaries of high-dimensional space : dimension of space = pixel intensity value

'W'
- quantify the badness of W : Loss Function
- searching through the possible W, find out the least bad W : Optimization

(x,y)의 데이터셋이 주어졌을 경우
{(x_i, y_i)} , for i in range N
단 x_i = image, y_i = label(예를 들어 CIFAR10에서 0~9)

Loss Function

L = 1/N * L_i( f(x_i, W), y_i )

Multi-Class SVM
- Binary SVM 의 generalization form (Multiple Classes)
- 알고리즘 : if(correct category score이 어떤 margin보다 더 크다면) : L=0, else : L = s_j - s_(y_i) +1
   > 여기서 s = classifier의 출력 score, s_(y_i) = score of true class(=y_i)
   > 여기서 1 : safety margin
Question
- 이미 엄청 높은 정답 score를 약간 바꿀 경우 : 변함 없음(score간 차이만 보기 때문)
- minimum loss = 0, maximum loss = inf
- 모든 score이 0에 가까울 경우 loss의 초기값 = #of classes -1
- 정답 클래스도 같이 다 더할 경우 loss = 기존 loss +1
- loss를 sum 이 아니라 mean으로 바꿀 경우 : rescaling(변함 없음)
- loss를 hinge loss(linear) 가 아니라 squared hinge loss로 바꿀 경우 : 변함 있음
- L=0으로 만드는 W는 unique? : NO
   > 2W 또한 L=0으로 만듦
   > classifier가 수많은 W중 어떤 W를 선택해야 하나?

Regularization
Occam's Razor : Simplest is the best, 즉 'penalize complexity of model not to fit the training data'
L(W) = 1/N * ( sigma(L_i( f(x_i, W), y_i ) + lambda*R(W) )
- hyper parameter인 lambda를 조절할 수 있음.
- 역할 1. 모델이 복잡해지지 않도록 하는 것
- 역할 2. soft constraint를 모델에 추가하는 것

- 종류 : L2 regularization(weight decay), L1 regularization, Elastic Net(L1+L2), Max norm regularization
- 특히 딥러닝에 특화된 regularization 종류 : Dropout, Batch Normalization, Stochastic Depth

L2 Regularization vs. L1 Regularization
- L2 : 가중치 행렬 W의 euclidean norm에 패널티를 주는 것
- L1 : 행렬 W가 sparcity 행렬이 되도록 한다.

ex. x = [1,1,1,1], w1 = [1,0,0,0], w2=[0.25,0.25,0.25,0.25]
- how to measure complexity?
 > L2 regression은 w2 (smaller norm) prefer (x 각 항의 decisions가 spread out independently되었으면 좋겠다!)
  >> if Bayesian : L2 regularization also corresponds MAP inference using a Gaussian prior on W
 > L1 regression은 w1 prefer (the number of 0가 모델의 복잡도를 결정)

Multinomial Logistic Regression (=Softmax Loss)
- scores := (unnormalized log) probabilities of the classes
P(Y|X) = e^s / sigma(e^s)
- min loss ~= 0(totally right), max loss ~= inf(0 on correct class)
- if all s ~0, loss 초기값 = log C

SVM vs. Softmax
- SVM : 정답과 그 외 클래스 간의 margin에 초점
- SoftMax : compute probability distribution

- if change score little bit, what happens to loss?
 > SVM : 변함없음(일정 마진만 넘으면 됨)
 > Softmax : 목적 자체가 correct class의 확률은 +inf로, incorrect class의 확률은 -inf로 만드는 것이므로 계속 변함

Optimization
- Loss 함수에서 가장 'bottom of the valley', 가장 아래쪽을 찾는 것이 관건
- iterative methods
  > random search(->useless)
  > local geometry of landscape(Which way to go to little bit down the hill?)
   >> follow the slope(negative gradient direction), update parameter vector
    >>> compute finite differences(유한 차분법, numeric) (->Super Bad, Super Slow, 디버깅에 쓰임)
    >>> compute dW (analytic)
- Gradient Descent
  > initialize weights
  > weights = weights - stepSize * gradient
  > stepSize = learning rate -> hyper parameter (training 할 때 가장 먼저 set해주어야 할 것)
  > gradient descent w/ momentum or Adam optimizer를 이용해서 더 빠르고 효율적으로 아래로 내려갈 수 있음.
- Stochastic Gradient Descent
  > 전체 데이터셋 개수가 엄청 클 때 사용
  > minibatch(power of 2로 정함) 에서 estimation of (loss의 전체합) 과 estimation of (true gradient) 계산

Image Features
파이프라인 : input image -> compute various feature of image -> concat feature -> input of linear classifier
가정 : feature representation do not update during training, training동안에는 linear classifier만 학습됨
feature representation ex 1. 극좌표계로 변환
feature representation ex 2. color histogram - globally하게 어떤 색이 dominate 하는가?
feature representation ex 3. HoG : 8x8 region 으로 나눈 다음 가장 dominate한 edge를 표현
feature representation ex 4. Bag of Words : CodeBook을 만든 다음 -> 각각의 visual words가 몇 번 나타나는가?

댓글