[cs231n] Lecture Summary _part I
Image Classification
K-Nearest Neighbors (KNN)
분류하고자 하는 point와 가장 가까운 K개의 point들의 label 중 그 수가 가장 많은 label을 사용한다.
test time에 training set 전체를 사용한다. parameter를 사용하지 않는다.
test time 때 매우 느려 이미지에 절대 사용하지 않는다.
Distance Metric
L1 distance를 사용하는가, L2 distance를 사용하는가에 따라 different assumption이 결과로 나온다.
L1이 coordinate system에 보다 더 영향을 받는다.
Linear Classification
test time에 training data로 학습한 knowledge를 사용한다. 이 knowledge가 가중치 W(parameter)이다.
이미지를 하나의 long column vector로 펼쳐서 input으로 사용한다.
위의 수식에서는 10 category가 필요하기 때문에 결과가 10으로 나오도록 차원을 맞췄다.
Problem: linear classification은 각 class 별로 하나의 template만 학습한다.
High dimensional의 관점에서 보면, Linear Classifier는 linear decision boundary를 놓아 하나의 category와 다른 나머지 category를 분류하는데 사용한다.
따라서 아래와 같은 경우들에서 하나의 linear line을 그려 파란색과 빨간색을 구분할 수 없다.
Loss Fuction
Loss fuction, 손실 함수는 현재 classifier가 얼마나 잘 작동하고 있는지를 보여준다.
Loss function L은 전체 dataset의 loss의 평균으로 계산한다.
두 가지 손실함수 SVM loss와 Softmax를 살펴보자.
Multiclass SVM loss
training data에 너무 맞게 학습되는 것(overfitting)을 피하기 위해 regularization을 같이 사용한다.
Softmax Classifier (Multinomial Logistic Regression)
Min possible loss Li = 0 = -log(1)
Max possible loss Li = infinity = -log(0)
초기값은 W가 작으므로 모든 s=0. 따라서 loss가 log(C)이다. 이것을 first iteration에서 디버깅 하는데 사용하기도 한다.
SVM loss는 correct score가 incorrect score의 margin보다 큰지만 고려하지만 Softmax loss는 모든 개별 데이터를 correct class의 probability mass로 고려해서 correct class는 +infinity로, incorrect class는 -infinity로 push 한다.
Regularization
Add term to loss
L1 regularization: measure model complexity by the # of zeros in the weigh vector
L2 regularization: spread the W across all the values are less complex. penalizing the euclidean norm of weigh vector
L1과 L2 중에서는 L2를 더 흔히 사용한다.
Elastic net (L1 + L2), Max norm regularization
(more specific to deep learning) Dropout, Bach normalization
Dropout
forward pass에서 radom하게 몇 개의 뉴런을 0으로 만든다. dropping 확률도 hyperparameter로 0.5가 흔히 사용된다.
network가 redundant representation을 갖도록 한다.
Test time에는 dropout probability를 mutiply하지만 test time에 scaling하지 않는 Inverted Dropout이 더 흔하다.
아래는 Inverted Dropout의 코드이다. 빨간색 box는 drop in forward pass 코드이다.
Batch Normalization
보통 fully connected layer 또는 convolutional layer의 다음에, non-linearity 이전에 넣는다.
test time에는 다시 계산해서 사용할 필요가 없다. training time에 estimate한 값을 test time에도 사용한다.
batch normalization도 regularization으로, batch norm을 사용하면 dropout을 사용하지 않는다.
Data Augmentation
random하게 image를 transform하여 훈련시키는 것이다.
Horizontal flips, Random crops and scales, Color jitter.... 등이 사용된다.
A common pattern
training: add some kind of randomness
testing: average out randomness
Examples:
- Dropout
- Batch Normalization
- Data Augmentation
- DropConnect
- Fractional Max Pooling
- Stochastic Depth
Optimization
final loss fuction을 최소로 만드는 W를 찾는 것
gradient를 사용해서 - gradient 방향으로 slope를 따라간다. Analytic gradient(수식으로 계산)를 항상 사용하고 Numerical gradient(일일이 데이터를 사용)는 디버깅을 위해서 사용한다.
Step size는 hyperparameter로 learning rate 라고 부른다.
SGD (Stochastic Gradient Descent)
at every iteration, we sample some small set of training examples, called a minibatch
32 / 64 / 128 이 보편적으로 쓰인다.
minibatch를 사용해 full sum의 추정치를 계산하고 true gradient를 예측한다.
Problems:
zero gradient나 saddle point 근처, slope가 매우 작은 곳에 stuck 될 수 있다.
loss가 한 방향으로 빠르게 변하고 다른 방향은 느리게 변하면 gradient가 jitter
실전에서 minibatch를 사용해서 loss와 gradient를 추정하기 때문에 gradient에 대한 정확한 정보가 없어 noisy가 생길 수 있다.
SGD + Momentum
velocity를 gradient의 running mean으로 보고 rho는 friction(마찰, 보통 0.9, 0.99)로 보아 velocity를 가지고 공이 언덕을 내려오는 것과 같이 생각한다.
Nesterov Momentum
velocity의 방향으로 step. 각 지점에서 gradient를 계산한다. original point로 돌아가서 이 둘을 mix해서 사용한다.
수식을 통해 보면 이해가 더 쉽다.
AdaGrad
grad_squared = 0
while True:
dx = compute_gradient(x)
grad_squared += dx * dx # Added element-wise scaling of the gradient based on the historical sum of squares in each dimension
x -= learning_rate * dx / (np.sqrt(grad_squared) + 1e-7)
2 coordinate이고 하나는 항상 high gradient, 다른 하나는 항상 small gradient이면 small gradient의 제곱을 더하고 divide하면 한 방향을 따라 accelerate movement할 수 있다. 다른 dimension에서 gradient가 크고 큰 수로 나누면 slow down 할 수 있다.
AdaGrad는 squared gradient를 계속 업데이트하기 때문에 분모가 계속 커져 step size를 작게 만든다. → continually decay learning rate, get stuck
RMSProp
AdaGrad를 보완한 것으로 궤적을 조정한다.
Adam
first, secon moment estimates가 0에서 시작 (first step이 매우 커지는 경우가 발생할 수 있다)하는 것을 막기 위해 bias correction을 한다.
Adam with
beta1 = 0.9, beta2 = 0.999
learning rate = 1e-3 or 5e-4
일 때 많은 모델에서 좋은 starting point로 작동한다.
Learning rate Decay
learning rate decay는 Adam보다 SGD Momentum에서 더 많이 사용된다.
learning rate decay는 second-order hyperparamenter로 처음에는 decay 없이 시작한다.
Secon-Order Optimization
First-Order Optimization은 linear approximation으로부터 gradient를 사용해서 approximation을 minimize하는 방향으로 나아간다. 그러나 Secon-Order Optimization은 곡선을 사용해서 minima로 step 한다.
Hessian을 사용하는 방법 이외에
Quasi-Newton methods(BFGS most popular), L-BFGS(Limited memory BFGS)도 있다.
Backpropagation
computational graph를 그려서 backpropagation을 계산한다.
1st step: calculate in forward
2nd step: 맨 마지막 단의 gradient는 1
3rd step: 각 노드에서, local gradient를 계산
4th step: chain rule을 적용해서 연결된 다음 노드(backward 방향)로 gradient를 보내 계산
Add gate: gradient distributor. 같은 값을 연결된 branch로 모두 보낸다.
Max gate: gradient router. 하나는 full value를 전달받고 다른 하나는 gradient가 0이다.
Mul gate: gradient switcher and scaler.
여러 개의 노드가 upstream의 노드 하나로 gradient가 전달되면 gradient들을 더한다.
Gradients for vectorized code
Neural Networks
여러 개의 layer를 쌓는 것이 가능하다.
2 layer 이면 f = W2 * max(0, W1*x)
activation function은 non-linearities이다. activation function들의 종류에 대해 알아보자.
Activation function
Sigmoid
범위를 [0, 1]로 줄인다.
Problem:
1. x가 매우 큰 음수이거나 양수이면 flat이 되어 gradient가 0이 된다.
2. sigmoid output이 zero-centered가 아니다. input이 모두 음수이거나 양수이면 가중치의 gradient가 항상 같은 방향으로 움직이기 때문에 W가 감소하기만 하거나 증가하기만 한다.
3. exp() is a bit compute expensive
tanh(x)
range [-1, 1], zero centered
Problem: 아직도 saturated 되면 gradient가 kill된다. (flat하기 때문)
ReLU (Rectified Linear Unit)
saturate 되지 않는다. very computational efficient
converge가 sigmoid, tanh보다 6배 빠르다.
Problem: Not zero-centered output. x < 0일 때 saturate
initialize를 잘못하면 절대 update되지 않을 수 있다.
Leaky ReLU
Will not 'die'
PReLU (Parametric Rectifier)
Leaky ReLU와 같다. alpha를 parameter로 다뤄 little bit more flexibility
ELU (Exponential Linear Units)
ReLU의 benefit을 모두 가지고 있다. close to zero mean output
Negative saturation regime compared with Leaky ReLU adds some robustness to noise
Problem: computation requires exp()
Maxout "Neuron"
generalizes ReLU and Leaky ReLU.
Linear Regime. saturate하지 않아 죽지 않는다.
실전에서는,
ReLU를 사용한다. (learning rate를 주의해서 설정)
sigmoid를 사용하지 않는다.
Convolutional Neural Networks
Fully Connected Layer
Convolution Layer
image를 미끄러지며 각 부분마다 dot product 하는 층
spatial structure가 보존된다. (fully connected layer처럼 이미지를 하나로 펼치지 않아도 된다.)
Weights가 작은 filter이다. filter의 depth는 input volume의 depth와 같다.
한 부분을 계산해서 나온 하나의 숫자가 보여 Activation map (=feature map)을 만든다. filter 한 개 당 activation map 한 개
layer를 거치고 난 뒤 output size를 어떻게 계산하는지 알아보자.
Output size: (N - F) / stride + 1
Zero pad the border
Deep network에서 activation map size를 빨리 줄이면 information를 잃는 것이므로 size를 우리가 원하는대로 조정하기 위해 input으로 들어온 것의 양 옆에 zero pad를 붙인다.
Output size: ((7 + 1 x 2) - 3) / 1 + 1 = 7x7
1x1 convolution layer
filter 개수에 따라 depth를 조절할 수 있다. depth를 제외한 output size는 input과 동일하다.
CONV layer에서 각 뉴런은 input volume의 같은 region을 보고 있다.
그러나 fully connected layer에서 각 뉴런은 full input volume을 본다.
Pooling Layer
size를 줄이거나 더욱 manageable하게 바꾸기 위해 사용한다.
depth에는 아무런 것도 하지 않는다. input depth = output depth
Max Pooling
overlap 안되게 stride를 조절하는 것이 보편적이다. 또한 보통 zero padding을 사용하지 않고 바로 downsampling한다.
Total Convolution Neural Network
ConvNet은 여러 개의 layer를 쌓아서 만들어지며 ConvNet 여러 개를 거칠수록 high level의 feature를 얻을 수 있다.
전체 Convolution Neural Network의 모습은 다음과 같다.
Data Preprocessing
이미지는 보통 zero centering은 하지만 normalize, PCA, whitening은 많이 하지 않는다.
In practice,
- substract the mean image
- substract per-channel mean
을 사용한다. test time에도 똑같이 적용한다.
Weight Initialization
W = 0이면 모든 뉴런이 같은 operation을 한다.
same output → same gradient → update in the same way → all neurons are exactly the same
따라서 작은 random number로 초기화했으나 deeper network에서는 각 layer에 작은 숫자의 W가 반복해서 곱해지면 빠르게 shrink하고 collapse되어 사용하지 않는다.
Xavier initialization
작은 input이 들어오면 → larger weight (큰 input이면 smaller weight)
W = np.random.randn(fan_in, fan_out) / np.sqrt(fan_in / 2)
Babysitting the Learning Process
step 1: Preprocess the data
step 2: Choose the architecture
step 3: Try to train
small regularization에서 시작해서 맞는 learning rate를 찾는다.
Loss가 거의 변하지 않는다면 → learning rate가 매우 작을 것이다.
Loss가 exploding 한다면 → learning rate가 너무 클 것이다. (NaN)
➡️ Rough range for learning rate we should be cross-validating is somewhere [1e-3 ... 1e-5]
Hyperparameter Optimization
Cross-validation strategy
몇 개의 epoch만 훈련시켜서 param이 잘 작동하는지 보고 다음에 longer running time으로 훈련시킨다.
NaN을 detect하는 tip) cost is ever > 3 * original cost 이면 NaN이 될 것이다.
Random Search vs. Grid Search
grid의 경우에는 3개 지점 밖에 없어 good region이 어디인지 놓칠 수 있다.
중요한 변수의 서로 다른 값의 많은 sample이 더욱 useful 하다.
Hyperparameters to paly with:
- network architecture
- learning rate, its decay schedule, update type
- regularization (L2 / Dropout strength)
Monitor and visualize
loss curve와 accuracy의 그래프를 그려서 살펴보는 것이 좋다.
Transfer Learning
data가 많지 않아도 transfer learning을 통해 CNN을 사용할 수 있다.
large data set을 가지고 있지 않으면,
하려는 task와 유사한 pretrained model을 다운로드해 현재 자신이 가지고 있는 data에 맞게 reinitialize하거나 fine tune하면 된다.
Deep learning frameworks가 pretrained model을 제공하고 있다. 아래 글에서 tensorflow framework를 사용해 transfer learning을 실전적으로 사용하는 법을 다루고 있다.