[Deep Learning] cs231n 7강 내용 정리 (1)
Optimization : Problems with SGD
(1) Loss function has condition number : ratio of largest to smallest singular value of the Hessian matrix is large
(sensitive to one direction and not sensitive to the other direction)
very slow progress along shallow dimension, jitter along steep direction.
(2) local minima and saddle point에서 zero gradient가 되어 gradient descent가 stuck 된다.
게다가 고차원이 될수록 saddle point가 local minima보다 심각한 문제임.
왜냐하면, local minima에선 모든 방향이 loss가 증가하지만 saddle point는 한 방향으론 loss가 증가하고 다른 방향으론 loss가 감소한다. (큰 dimension엔 frequent 하게 발생.)
게다가 near the saddle point도 문제가 된다. (slope가 평평해서 gradient가 0에 가까움.)
Local minima : non-convex에서 gradient는 음수. (어느 방향이든 감소. 극대점.) convex에선 gradient가 양수. (어느 방향이든 증가. 극소점.) <-> 방향에 따라 gradient가 다른 것 (saddle point)
(3) mini batch를 이용하면 gradient에 대한 true information이 아닌 noisy estimate를 얻음.
이 noise가 mess up gradient를 함. (Vanila SGD가 minima에 가는데 오랜 시간이 소요된다.)
SGD의 대안으로 나온 해결책
(1) SGD + Momentum : 원래 빈번히 가던 direction으로 가고자 하는 관성.
v(t+1) = rho*v(t) + compute gradient(x)
x(t+1) = x(t) - learning rate * v(t+1)
saddle point에서 gradient가 0이더라도 velocity는 유지되어 saddle point를 뛰어 넘을 수 있음.
minima로 가는데 필요한 step이 훨씬 줄어든다.
high conditional number 문제를 해결하고, noise가 averaged out 된다. + saddle point 해결!
Momentum을 업데이트 하는 두 가지 방법
(1) momentum update
(2) nesterov momentum : momentum update보다 좀 더 나중 시점의 gradient.
velocity로 옮긴 후 gradient로 옮김. (gradient 계산을 나중에 한다.
convex 함수에 유용하다.
velocity의 initialization = 0 (velocity -> weighted sum of gradient)
v(t+1) = rho * v(t) - learning rate * df(x(t)+rho*v(t))
x(t+1) = x(t) + v(t+1)
근데 이렇게 하면 x(t)와 df(x(t))가 아니라 x(t)+rho*v(t)로 하니까 annoying! 계산이 복잡.
v(t+1) = rho * v(t) - learning rate * df(x(t))
x(t+1) = x(t) + v(t+1) + rho(v(t+1)-v(t))
으로 바꿔서,
dx = compute_gradient(x)
old_v = v
v = rho*v - learning_rate * dx
x += -rho * old_v + (1+rho) * v
velocity가 minima를 통과할 수도 있는데 sharp minima에선 그럴 수 있지만 대부분의 이런 minima는 overfit일 가능성이 높다.
(2) AdaGrad : velocity 대신 gradient의 제곱을 사용한다.
dx = compute_gradient
grad_squared += dx * dx
x -= learning_rate * de / (np.sqrt(grad_squared) + 1e-7)
1e-7은 0으로 나눠주지 ㅇ낳기 위한 상수.
(1) high condition number 문제는 위 아래로 많이 바뀌는 gradient는 큰 수로 나누어서 늦추고, 잘 변하지 않는 것은 작은 수로 나누어서 속도를 빠르게 한다.
(2) saddle point : non-convex에서는 stuck.
step size는 gradient가 점점 쌓여서 작아진다.
(3) RMSProp : squared_gradient가 축적만 되지 않고 좀 delay 할 수 있도록 decay rate를 도입함.
grad_squared = decay_rate * grad_squared + (1 - decay_rate) * dx * dx
dx = gradient
(4) Adam
velocity와 squared gradient를 둘 다 이용한다. (squared gradient는 decay rate 있는 것을 보니 RMSProp과 좀 더 유사)
첫 timestep은 very very large step.
bias correction : bias의 값을 보정
SGD, SGD+Momentum, Adagrad, RMSProp, Adam -> learning rate가 hyper parameter이고, lr을 천천히 decay 시켜서 minima에 까깝게 도달할 수 있도록 설정해야 한다.
decay : exponential decay, 1/t decay
(1) First-order optimization
- use gradient form linear approximation
- step to minimize the approximation
(2) Second-order optimization
- use gradient and Hessian to form quadratic approximation
- step to the minima of the approximation
(doesn't have lr -> stepping right to the minimum of quadratic. always step to the minima, at every time step.
그러나, Deep learning에 사용하기엔 계산량이 너무 많아서 힘들다. Hessian은 O(N^2) element를 가지고 있고, inverting은 O(N^3) 정도가 소요된다.
BFGS(Quasi-Newton method) : Hessian을 invert하지 않고 approximate inverse Hessian with rank 1 update over time (O(n^2))
L-BFGS : does not form/store the full inverse Hessian
usually works very well in full batch, deterministic mode.
does not transfer very well to mini-batch setting.
Model Ensemble
(1) train multiple independent models
(2) at test time average their results
INSTEAD of training independent models, use multiple snapshots of a single model during training
INSTEAD of using actual parameter vector, keep a moving average of the parameter vector and use that at test time (Polyak averaging)
Regularization : Add term to loss. Training에선 add random noise, test에선 marginalize over the noise
(1) L2 regularization, L1 regularization, Elastic net(L1+L2)
(2) Dropout : randomly set some neurons to zero
forces the network to have a redundant representaion
prevents co-adaptation of features
overfit 피하는데도 도움이 된다.
Dropout is training a large ensemble of models. each binary mask is one model.
Want to "average out" the randomness at test-time (다시 p를 곱해준다.)
그래서 test의 결과에 dropout probability p를 곱해줌.
반대로, train에서 원래 randomness를 부과했던 p를 다시 나누어줌으로써 p를 상쇄시킬 수 있음.
Batch norm도 similar regularization effect를 가지므로 dropout과 동시에 사용할 필요는 없음. p를 통해 dropout은 regularization의 정도를 control 할 수 있지만, batch norm은 control이 불가능하다. (Normalize using stats from random minibatches during train and use fixed stats to normalize during test)
(3) Data augmentation
데이터의 양을 증가시키는 것.
Horizaontal flips, random crops and scale, color jitter, translation, rotation, stretching, shearing, lens distortions
(4) DropConnect : zero out weight matrix
(5) Fractional Max Pooling
(6) Stochastic Depth : drop layer during train and use whole net during test.
Transfer Learning : 이미 많은 양의 data로 train된 모델을 이용하는 것.
(1) 적은 양의 data가 있다면 : 마지막 layer를 reinitialize 하고 train 시킴. Use Linear Classifier on top layer.
(2) 많은 양의 data가 있다면 : 마지막 Max pooling layer 이후의 모든 FC를 train 한다. (fine tuning. fine tuning을 할 때는 기존의 learning rate의 0.1 정도로 하는 것이 매우 좋음.) finetune a few layers.
만약 dataset이 서로 많이 다른데 많은 양의 data 있다면 finetune a large number of layers.
Transfer learning을 하면 FC전의 layer들은 generic하고 FC layer들은 specific 하다고 볼 수 있음.