mini-batch SGD

loop:

1. Sample a batch of data

2. Forward prop it through the graph, get loss

3. Backprop to calculate the gradients

4. Update the parameters using the gradient

 

Training Neural Networks (a bit of history)

- 1957, Mark 1 Perceptron -> back prop 불가

- 1960, perceptron의 stacking, Adaline/Madaline

 

1960~1980 신경망의 1번째 암흑기.. 

 

- 1986, Rumelhart et al, First time back-propagation became popular

-> 네트워크가 커질 수록 잘 동작이 안됨..

 

~ 2000 중반, 신경망의 2번째 암흑기 

 

- 2006, Hinton and Salakhutdinov

-> Restricted Boltzman Machine(RBM)을 이용하여 pretraining을 도입

-> 하나로 통합 후 backprop, 그 후 finetuning 사용

=> 제대로 동작하는 첫번째 backprop

 

 황금기(폭발적인 발전)

- 2010, Context-Dependent Pre-trained Deep Neural Networks for Large Vocabulary Speech Recognition

- 2012, Imagenet classification with deep convolutional neural networks

요인, 요소 : weight 초기화 방법 발전, GPU 환경, 데이터 증가

 

Activation Functions

 

Sigmoid

- 넓은 범위의 숫자들을 [0,1] 범위의 숫자로 squash해준다.

- 전통적으로 자주 사용해왔지만 더이상 잘 사용하진 않는다.

 

문제점

- 뉴런이 포화되어(0 또는 1에 가까워짐) gradient를 없애버릴 수 있다. (vanishing gradient)

(x의 값이 꽤 크거나 작은 경우에는 local gradient가 0에 가까워지게 됨 -> 그래프에서 saturated regime인 구역)

- Sigmoid의 결과는 zero-centered가 아니다. -> slow convergence를 가져오게 됨.

(w의 gradient가 항상 all positive이거나 negative이기 때문)

- exp()가 연산적으로 비쌈

 

 

tanh(x)

- [-1, 1] 범위로 숫자들을 squash 해준다.

- zero centered 되어 있다. 

- 여전히 뉴런이 포화되어(0 또는 1에 가까워짐) gradient를 없애버릴 수 있다. (vanishing gradient)

 

ReLU

 

- x가 양수인 지점에서는 포화되지 않음

- 연산적으로 효율적이다.

- sigmoid/tanh에 비해 수렴되는 속도가 6배정도 빠르다.

 

문제

- zero-centered가 아니다.

- 음수인 경우에 vanishing gradient가 발생

 

dead ReLU는 learning rate가 너무 크거나, weight 초기화가 운이 나쁘게 잘못되었을 때 발생함.

=> 이를 방지하기 위해 작은 양수 값으로 초기화하는 경우도 있음

 

Leaky ReLU

- saturate가 일어나지 않음

- 효율적인 연산

- converge가 빠름

- will not 'die' (gradient..)

 

Parametric Rectifier

alpha도 학습할 수 있음

Exponential Linear Units(ELU)

- ReLU의 장점을 가지고 있음

- not die

- zero mean outputs에 가까움

- 연산에서 exp()을 가지고 있음

 

Maxout "Neuron"

- Does not have the basic form of dot product -> nonlinearity

- ReLU와 Leaky ReLU를 일반화

- saturateX, note die

- 2배로 증가하는 연산과 파라미터

 

결론

- ReLU를 사용, 단 learning rate에 주의

- Leaky ReLU/ Maxout / ELU를 실험적으로 사용

- tanh를 실험적으로 사용하지만 기대X

- sigmoid는 사용X

 

Data Preprocessing

단, 이미지 데이터에서는 정규화는 진행하지 X

이미지는 기본적으로 [0~255]안에 들어가 있기 때문

 

PCA(주성분 분석), whitened data

=> 사실 이미지에 있어서 둘다 사용은 X

 

 

이미지에서는 정규화, PCA, whitening은  흔하게 사용하지 않고, 사실상 zero-centered만 신경 쓰면 된다. 

- 이미지의 평균 값을 빼준다. (e.g. AlexNet)

- 채널별 평균 값을 빼준다. (e.g. VGGNet)

 

Weight Initialization

Q : 만약 W=0으로 초기화 되어 있다면?..

모든 뉴런들이 동일한 연산을 수행하고, back prop을 수행함.

small random numbers

=> 네트워크가 작을 때에는 동작하지만, 커지게 되면 문제가 발생함.

standard variance이 0으로 수렴하게 되고 결과적으로 모든 activation이 0이 되어버림

=> vanishing gradient가 발생

 

0.01 대신 1을 쓴다면 거의 모든 뉴런들이 saturate 됨. -> Gradient가 0이 되어버림

 

Xavier initialization

input의 개수가 많으면 weight가 작아짐, 개수가 적으면 weight가 커짐

 

- 문제 : ReLU를 사용할 때 문제가 생김. (but when using the ReLU nonlinearity it breaks.)

 

He et al., 2015 (note additional /2)

 

 

Batch Normalization

vanishing gradient가 발생하지 않도록 하는 해결방법 중 하나

(activation 함수 변화, 가중치 초기화 방법이 아니라 학습하는 과정 자체를 안정화하는 것을 목표로 함.)

 

각 layer를 거칠 때마다 normalization을 진행

 

정규분포 적용

 

 

\

보통 Fully connected layer와 activation layer 사이에 위치하게 된다. 

 

 

 

1. Normalize

2. 정규화 된 것을 조정(r-> 스케일링 B->shift)

 

 

전체적인 flow

장점

- gradient flow를 향상

- 큰 lr도 허용시켜준다.

- 초기화에 대한 강한 의존성을 상쇄시켜준다. 

- regularization의 효과가 있음

 

주의

- training, test 할때 batch normalization을 다르게 해 줘야 한다. 

- mean/std를 구할 때 training은 batch를 기준, test는 전체를 기준 

 

Babysitting the learning process

1. 데이터 전처리 (zero-centered)

2.  choose the architecture (sanity check)

 

훈련 전, 데이터 중 일부만 가져와 regularization을 끄고 simple vanilla 'sgd'를 사용해 overfitting이 되는지 확인

(back prop이 잘 작동하고 있다는 뜻)

 

loss not going down : learning rate too low

loss exploding : learning rate too high

 

cross validation을 사용해 적절한 learning rate를 알아내야 함.

 

Hyperparameter Optimization

cross-validation 전략

First stage: only a few epochs to get rough idea of what params work

Second stage: longer running time, finer search

 

First stageg

 

-> random search 방법

 

기본적으로 grid search는 오히려 최적화된 parameter를 찾기 어렵다.

 

 

Hyperparameters to play with

- network architecture

- learning rate, its decay schedule, update type

- regularization (L2/Dropout strength)

 

 

hyperparameter를 조정한 뒤 loss curve를 관찰해야 한다.

 

 

다양한 그래프

 

- bad 초기화로 다음과 같은 그래프가 나옴.

hyperparameter를 조정한 뒤 accuracy를 관찰해야 한다.

 

 

weight updates/ weight magnitudes 를 관찰해야 한다.

https://ocw.mit.edu/courses/18-06-linear-algebra-spring-2010/resources/lecture-5-transposes-permutations-spaces-r-n/

 

Lecture 5: Transposes, permutations, spaces R^n | Linear Algebra | Mathematics | MIT OpenCourseWare

To account for row exchanges in Gaussian elimination, we include a permutation matrix P in the factorization PA = LU. Then we learn about vector spaces and subspaces; these are central to linear algebra. These video lectures of Professor Gilbert Strang tea

ocw.mit.edu

해당 강의를 참고하여 공부한 내용을 정리하였습니다.

새 창에서 열기

https://ocw.mit.edu/courses/18-06-linear-algebra-spring-2010/resources/lecture-4-factorization-into-a-lu/

 

Lecture 4: Factorization into A = LU | Linear Algebra | Mathematics | MIT OpenCourseWare

This session explains inverses, transposes and permutation matrices. We also learn how elimination leads to a useful factorization A = LU and how hard a computer will work to invert a very large matrix. These video lectures of Professor Gilbert Strang teac

ocw.mit.edu

해당 강의를 참고하여 공부한 내용을 정리하였습니다.

새 창에서 열기

 

 

지난 강의 복습

즉,  optimization은 loss를 최소화하는 W를 찾아가는 과정이다. (Parameter update)

 

 

Computational Graph

Backpropagation

 

- Forward Pass

오른쪽처럼 Graph로 표현이 가능하고 왼쪽->오른쪽으로 가는 방향을 FP(Forward Pass)라고 한다.

 

 

Input에 대한 Gradient를 구하면(Output에 얼마정도의 영향을 미치는지)

매개변수 q를 사용한다. Want를 얻기 위해서는 BP(Backward Pass, Backpropagation)이 필요하다.

 

 

f에 대한 gradient를 구해준다. 

빨간 숫자가 f에 대한 gradient를 의미하게 된다.

 

 

 

Forward pass를 하는 과정에서 local gradient를 구할 수 있다. 

Backward pass를 하는 과정에서 global gradient를 구할 수 있다.

=> 결국 local gradient와 global gradient를 곱해 gradient를 구할 수 있다. 

Backpropagation = Backpropagation

 

다른 예제로 다시 확인

 

 

gradient 계산

 

- sigmoid function

복잡한 계산 없이 자기 자신의 값으로 미분값을 표현 가능하다.

미분값이 자기 자신으로 표현이 된다.

 

- Backward flow의 패턴

add gate : gradient를 그대로 같은 값으로 전파해준다. local gradient = 1

max gate : 큰 것만 곱하기 1을 하는 결과가 되어 하나만 취하게 된다. 

mul gate : 곱하는 것의 반대쪽 gradient로 바뀌게 된다. 

 

 

- Gradient가 분기 되었을 때는 더하면 된다.

 

 

- Implementation : forward / backward API

 

forward pass시의 local gradient를 저장해놓기 위해 self.x, self.y로 저장.

이렇게 수많은 layer들을 레고 조립하듯이 구성하는 과정을 거친다.

 

 

x,y,z가 벡터인 경우 dL/dz는 벡터가 되고, dz/dx는 matrix가 된다. 

 

 

Q : what is the size of the Jacobian matrix?

A : 4096X4096

 

Q2: what does it look like?

A: identity matrix와 유사하지만, 모두 1이 아닌 구조

 

- mini-batch를 사용한 경우

mini batch size가 100인 경우 [409,600 x 409,600] matrix가 된다.

 

Neural Network

non-parametric approach : one class - one classifier

parametric approach : one class - multi classifier

 

- 뉴런과의 비교

 

-Activation Function의 종류

ReLU를 사용하는 것이 일반적

 

신경망의 종류

 

more neurons -> more capacity(분류 능력)

하지만 오버피팅이 되지 않도록 조절하기 위해서 신경망의 사이즈를 조절하는 것이 아니라, regularization을 조절해야한다. 

 

neural networks: bigger = better (but might have to regularize more strongly)

https://ocw.mit.edu/courses/18-06-linear-algebra-spring-2010/resources/lecture-3-multiplication-and-inverse-matrices/

 

Lecture 3: Multiplication and inverse matrices | Linear Algebra | Mathematics | MIT OpenCourseWare

This lecture looks at matrix multiplication from five different points of view. We then learn how to find the inverse of a matrix using elimination, and why the Gauss-Jordan method works. These video lectures of Professor Gilbert Strang teaching 18.06 were

ocw.mit.edu

해당 강의를 참고하여 공부한 내용을 정리하였습니다.

새 창에서 열기

https://ocw.mit.edu/courses/18-06-linear-algebra-spring-2010/resources/lecture-2-elimination-with-matrices/

 

Lecture 2: Elimination with matrices | Linear Algebra | Mathematics | MIT OpenCourseWare

This session introduces the method of elimination, an essential tool for working with matrices. The method follows a simple algorithm. To help make sense of material presented later, we describe this algorithm in terms of matrix multiplication. These video

ocw.mit.edu

해당 강의를 참고하여 공부한 내용을 정리하였습니다.

새 창에서 열기

2016 cs231n 강의 내용을 정리해 올린 글입니다.

 

 

TODO

1. 훈련 데이터의 score에 대해 불만족하는 정도를 정량화하는 loss function을 정의한다. 

2. loss function을 최소화하는 파라미터들을 효율적으로 찾는 과정 (optimization)

 

 

- Loss Function

3개의 훈련 예시, 3개의 클래스, f(x, W) = Wx 에 의해 도출된 score가 표시되어 있다.

 

 

1. SVM을 활용한 Hinge loss

Hinge loss를 구할 수 있는 form이다. S_j는 잘못된 레이블의 스코어, S_yi는 올바른 레이블의 스코어를 의미한다.  1은 safey margin을 의미한다.

 

고양이에 대한 Hinge loss 값을 구해보면

max(0, 5.1-3.2+1) + max(0, -1.7-3.2+1) = 2.9+0 = 2.9 가 된다.

 

다음과 같이 Hinge loss 값들을 구할 수 있다.

 

이제 loss값들을 더해 총클래스의 수로 나눠주면 (2.9+0+10.9)/3 = 4.6을 도출해낼 수 있다.

 

Q: what if the sum was instead over all classes? (including j = y_i)

 

고양이 클래스를 예시로 들면

max(0, 5.1-3.2+1) + max(0, -1.7-3.2+1) + max(0, 3.2-3.2+1) =  2.9+1+0 = 3.9 

-> loss값이 1 늘어나게 된다. -> 평균 loss값도 1 늘어나게 된다.

 

Q2: what if we used a mean instead of a sum here?

큰 의미는 없을 것.. 

 

Q3: what if we used?

squared hinge loss라고도 불린다.

 

non-linear 한 방식이므로 차이가 존재..

 

Q4: what is the min/max possible loss?

최저값은 0이 된다. 최댓값은 무한대

 

Q5: usually at initialization W are small numbers, so all s ~= 0. What is the loss?

max(0, 0-0+1) +  max(0, 0-0+1) ~= 2

loss는 2가 될 것 이다. 일반화를 하면 class-1 값이 초기의 loss 값이 될 것이다.

이를 통해 초기의 학습이 잘 진행되고 있는지 확인할 수 있다. (sanity check)

 

numpy 코드로 표현하면 다음과 같다.

 

위의 수식을 정리한 것

다음과 같은 loss에서 사실 bug가 존재한다. loss 0을 만족하는 W를 찾았다고 하였을 때 W는 유일하지 않다.

 

loss값을 0으로 만드는 W가 유일하지 않다는 예시

유일한(unique)한  Weight값을 결정해주기 위해서 regularization이라는 개념을 도입한다.

 

A way of trading off training loss and generalization loss on test set

 

Data Loss = > 학습용 데이터들의 최적화 담당

Regularization loss => 테스트 데이터들의  일반화 담당

=> Data에도 가장 fit 하고 가장 최적화(작은) W값을 추출하게 됨.

 

 

일반적으로 사용되는 Regularization 방법

 

 

다음과 같이 결과가 1로 같지만, L2 Regularization은 w_2를 선호하게 된다.(Weight를 최대한 Spread out)

-> diffuse over everything

 

 

 

 

2. Softmax를 활용한 Cross entropy loss

 

 

 

계산을 따라가며 확인해보면

마지막 확률은 합이 1이 된다.

Q: What is the min/max possible loss L_i?

확률의 범위 (0~1), -log(0) = 무한대, -log(1) = 0 이기 때문에 (0~무한대)의 범위를 가진다.

 

Q5: usually at initialization W are small numbers, so all s ~= 0. What is the loss?

e^0 = 1이 되고, normalize 하면 0.33이 되면 -log(0.33)이 된다.

 

다음과 같이 softmax와 svm을 비교할 수 있다.

Q: Suppose I take a datapoint and I jiggle a bit (changing its score slightly). What happens to the loss in both cases?

A : svm에는 +1 (safety margin)이 있어 robustness를 만족하게 된다. 따라서 loss가 동일하지만, softmax에서는 모든 수들을 고려하여 loss를 만들기 때문에  변화하게 된다.

 

 

정리

 

 

- Optimization

strategy #1 : Random search

정확도 15.5%... 최악이다.,

 

strategy #2: Follow the slope

1차원의 경우 함수의 미분으로 표현가능, 다차원의 경우 벡터의 형태로 표현 가능

 

Numerical gradient 계산 과정

장점 : 코드로 작성하기에는 쉽다.

단점 : 근사치를 가지게 된다. 평가 시간이 매우 길다.

 

 

 

사실 loss는 W의 함수이기 때문에 미분만 구하면 쉽게 구할 수 있다. => Analytic gradient

장점 : 정확하고 빠르다.

단점 : 코드로 작성하면 에러가 날 가능성이 있다.

 

실제 사용할 때는 Analytic gradient를 사용하고 체크할 때에만 numerical gradient를 사용하면 된다. 이를 gradient check라고 한다. 

 

- Gradient Descent ( Full-batch Gradient Descent)

step_size = learning rate로 hyperparameter이다.

 

 

- Mini-batch Gradient Descent

 

 

mini-batch를 사용하였을때, 시간에 따른 loss값 특정 데이터만 사용하여 파라미터를 업데이트 하였기 때문에 노이즈가 생긴다. 장기적으로는 서서히 내려간다.

 

 

mini-batch  Gradient  Descent의 대표적인 예로는 stochastic gradient descent가 있다.

파라미터를 업데이트하는 방식으로는 Gradient Descent만 있는 것이 아니라 

momentum, Adagrad, RMSProp, Adam,... 등이 있다.

 

 

- Aside : Image Features

전통적인 방법 : 이미지 -> 특징 추출 -> linear classifer 적용

 

특징 추출 방법 

1. color (Hue) Histogram

 

2. HOG/SIFT features

8x8 픽셀로 구성되어 있는 구역 내에 edge의 방향을 특징으로 추출

 

3. Bag of Words

 

딥러닝 접근 방법 : 특징 추출을 하지 X, 이미지 자체를 모델에 넣어 결과를 반환해줌

 

 

 

 

https://ocw.mit.edu/courses/18-06-linear-algebra-spring-2010/resources/lecture-1-the-geometry-of-linear-equations/

 

 

Lecture 1: The geometry of linear equations | Linear Algebra | Mathematics | MIT OpenCourseWare

A major application of linear algebra is to solving systems of linear equations. This lecture presents three ways of thinking about these systems. The “row method” focuses on the individual equations, the “column method” focuses on combining the co

ocw.mit.edu

 

 

 

해당 강의를 참고하여 공부한 내용을 정리하였습니다.

 

새 창에서 열기

+ Recent posts