데이터와 AI / NOTE 26

학습과 최적화

Training & Optimization

경사하강법, 모멘텀, 적응적 갱신과 정규화 관련 노트입니다.

♫ 이 문서 듣기

개념에서 수식으로

먼저 이해할 내용

모델의 수식이 정해져도 계수가 자동으로 적절해지는 것은 아니다. 학습은 예측 오차를 계산하고 계수를 바꾸는 절차를 반복하는 과정이다. 이 글은 갱신 방향·이동 크기·데이터 묶음·정규화를 각각 나누어 다룬다.

기호를 먼저 읽기

θ
학습으로 바꿀 모델 매개변수
J(θ), ℓ
오차를 하나의 값으로 모은 목적함수
∇J
매개변수에 대한 목적함수의 기울기
α
갱신의 이동 크기
v, r
이전 기울기 또는 그 제곱의 누적 정보
β
현재 값과 이전 누적값의 비중
μ, σ²
평균과 분산

이 글의 흐름

기본 경사하강법과 데이터 묶음의 차이를 이해한 뒤, 이동평균·모멘텀·적응형 갱신을 비교한다. 마지막에는 입력과 중간값의 정규화가 학습식에 어떻게 들어가는지 살펴본다.

주제와 표기

Training

Optimization for deep learning

모델의 예측과 학습할 계수를 분리한다

f(x;θ)는 입력 x와 계수 θ를 받아 예측값을 만든다. 학습 데이터의 정답과 예측을 비교해 J를 계산하고, θ를 바꾸어 J를 줄인다. 입력 데이터 자체와 학습으로 조정할 변수를 먼저 구별한다.

Parameterized Model
y^=f[x;θ]
input : x
parameters:θ
Training Data = {(x¯1, y1), …, (x¯N, yN)} = {(X, y¯)}
Error function J=12Nn=1N(yny^n)2
minimizeθ12Nn=1N(yny^n)2
GradientJθ

Gradient descent

기울기의 반대로 조금 이동한다

현재 θ에서 목적함수의 기울기를 구하고 α를 곱해 뺀다. 기울기는 어느 방향이 증가 방향인지 알려주고 α는 그 방향으로 얼마나 이동할지 결정한다. α가 양수라는 조건과 현재 지점에서 미분을 평가한다는 뜻을 함께 읽는다.

원본 도해
Consider the objective function : J[θ] : RDR . (e . g ., J[θ] = 1/N∑_ (n = 1)N | f[xn;θ] - yn |^2)

A first-order iterative optimization algorithm for finding a local minimum of the objective function J[θ]

Moves from the current values of parameters, θk, in the opposite direction of the gradient of the objective function J[θ] w.r.t. the parameters, evaluated at θk

θk+1θkα[J[θ]θ]θ=θk
currentgradient:[J[θ]θ]θ=θk
where α is learning rate (step size)
Taining set = {(x¯1, y1), (x¯2, y2), …, (x¯N, yN)} = (X, y¯), where xnRD and ynR
Batch=(X,y¯)
Mini - batch of size M = (X^{m}, y¯m)
Xm={x¯m,,x¯m+M1},y¯m={ym,,ym+M1}

(Full) Batch Gradient Descent ⇔ Vanilla Gradient

Resort to entire training dataset to compute the gradient of the object function

전체 데이터와 일부 데이터의 차이를 읽는다

배치 방식은 전체 데이터로 한 번의 기울기를 계산하고, 미니배치는 일부 샘플 묶음으로 갱신한다. 묶음이 하나의 샘플이면 한 샘플의 오차가 바로 갱신에 반영된다. 모델식이 달라진 것이 아니라 한 번에 기울기를 계산하는 데이터 범위가 달라진 것이다.

θk+1θkα[J[θ;X,y¯]θ]θ=θk

The accuracy of the parameter update is high but it can be slow

Intractable for datasets that do not fit in memory

Does not allow us to update the model online (with new examples on the fly)

Mini-Batch Gradient Descent ⇔ Stochastic Gradient descent (SGD)

Consider the objective function that is the sum of errors evaluated on each batch
J[θ;X,y¯]=1NMm=1NMJ[θ;Xm,y¯m]
where X^{m} and y¯m are training examples in mini - batch m and Nm is the number of mini batches
Mini - batch gradient descent updates parameters
θk+1θkα[J[θ;Xk,yk]θ]θ=θk
Or using a batch of size 1
θt+1θtα[J[θ;x¯t,yt]θ]θ=θt

Gradient=Steepest Descent Direction

국소 근사에서 이동 방향을 구한다

현재 값 주변에서 목적함수를 일차식으로 근사하면, 변화량의 효과는 기울기와 이동벡터의 내적으로 표현된다. 방향벡터의 길이를 정해 놓고 이 값을 작게 만드는 방향을 찾는다. 이때 목적함수를 줄이는 방향은 기울기 자체가 아니라 음의 기울기 방향이라는 앞뒤 정의를 함께 확인한다.

Let dθ = εv¯ . Then, serach for the direction v¯ that minimizes
J[θ+dθ]J[θ]+[J[θ]]Tdθ=J[θ]+ϵ[J[θ]]Tv¯
under the constraint that
|v|2=i,jGi,jvivj=v¯TGv¯=1

By the Lagrangian method, we have

v¯[ϵ[J[θ]]Tv¯+λ(1v¯TGv¯)]=0
leading to
v¯=ϵ2λG1J[θ]
When the space isEuclidean and the coordinate system is orthogonal, then G = I, indicating that the gradient is the steepest descent direction

Convex function

볼록성은 두 점 사이의 함수값 관계이다

볼록함수 식은 두 점의 함수값을 섞은 값과 두 점을 섞은 위치의 함수값을 비교한다. 그림의 굽은 모양을 외우기보다 부등호의 어느 쪽이 큰지 읽는다. 안장점은 단순히 값이 작거나 큰 점과 다른 형태로 원문에서 구별한다.

αf[x1]+(1α)f[x2]f[αx1+(1α)x2]
Concave
Saddle Points

Neural Network fθ[x]

반복 갱신의 방향과 크기를 따로 기록한다

θₖ에 이동방향 v와 크기 α를 곱해 더하면 다음 θ가 된다. argmin은 이 반복의 목표가 되는 매개변수를 뜻한다. 중간 유도에서 기호가 바뀌어 보이는 줄은 정의와 차원을 확인하며 읽고, 모든 줄이 별도 조건 없이 같은 식이라고 확대하지 않는다.

θ : layer sum
Sample (Training Set) : S
Training:Algorithm(S,)=θ,fθ[x]
loss:[fθ[x],y]
square loss: =12Nn=1N(fθ[xn]yn)2
argminθ[fθ[x],y]
argminθ[θ]

Iterative methods

initialθ0θ1θ2θkθ
θkθk1+αυk1
step size : α
direction:υk1
[θ+dθ]<[θ]
dθ=ϵυ,|υ|2=1
[θ+dθ][θ]+T[θ]dθ(firstorderapproximation)
=[θ]+T[θ](ϵυ)
minimizeυT[θ](ϵυ)+λ(1υTυ)
υ[T[θ](ϵυ)+λ(1υTυ)]=ϵ[θ]2λυ=0
2λυ=ϵ[θ]
λ=ϵ2λ[θ]

Problem

하강 방향인지 내적의 부호로 확인한다

현재 기울기와 v의 내적이 음수이면 작은 이동에서 목적함수가 줄어드는 방향임을 판단할 수 있다. v를 음의 기울기로 두면 내적이 음의 노름 제곱이 된다. 다만 기울기가 0인 경우는 엄격한 감소가 보장되는 경우와 구별한다.

We consider the objective function (loss function, error function) J[θ] : RDR
For instance, the square loss is given by
J[θ]=12Nn=1N|f[xn;θ]yn|2
Traning (or learning) involves finding a minimizer of J[θ]
argminθJ[θ]

General form of iteration methods

θk+1θk+αkvk
step size : αk
direction:vk

Definition

For a given point θ∈RD, a direction v∈RD is called a decent direction if there exists α¯ >0
such that
J[θ+αv]<J[θ],α(0,α¯)

Lemma

For a point θ∈RD, any direction v satisfying
<J[θ],v>=JT[θ]v<0
is a descent direction
Certainly - ∇J[θ] is a descent direction, since
<J[θ],J[θ]>=|J[θ]|2<0
Suppose that you are sitting at a point θ∈RD and looking at the value of the function J[θ] in all directions around you .
The direction with the maximum rate of decrease is along - ∇J[θ]

Exponentially Weighted Moving Average

최근 값에 더 큰 비중을 두어 누적한다

vₜ=βvₜ₋₁+(1−β)θₜ는 이전 평균과 새 값을 섞는 식이다. 이를 반복해서 펼치면 오래된 값에는 β의 더 높은 거듭제곱이 붙는다. β=0.9에 대한 1/(1−β)=10은 대략적인 기억 길이를 설명하는 관계이며, 정확히 최근 10개만 사용하는 창 평균은 아니다.

Suppose that we are given θ1, θ2, θ3, …
Moving average of θt is calculated as
vt=βvt1+(1β)θt
β[0,1],β=0.9
v0=0
v1=βv0+(1β)θ1=(1β)θ1
v2=βv1+(1β)θ2=(1β)(βθ1+θ2)
vt=(1β)(βt1θ1+βt2θ2++θt)
≈which approximately average over 1/(1 - β) samples
β=0.911β=10

Bias Correction

초기값의 영향을 보정한다

누적값을 0에서 시작하면 초기에 값이 작아지는 효과가 생긴다. vₜ를 1−βᵗ로 나누는 식은 이 초기 편향을 보정하기 위한 것이다. 원문의 수치 예시에는 근삿값처럼 읽어야 하는 줄이 있으므로, 뒤의 등호를 모두 정확한 산술 등식으로 해석하지 않는다.

Use vt/(1 - βt) instead of vt (useful during initial phase)
v110.9=10v1
v210.92=5v2
v1010.910=v10

Gradient Descent with Momentum

모멘텀은 기울기의 누적 방향을 사용한다

매번 현재 기울기만 쓰는 대신 이전 누적 기울기와 새 기울기를 섞는다. 여러 단계에서 같은 방향이 유지되면 그 경향이 갱신에 남고, 방향이 자주 바뀌면 일부 변화가 서로 완화된다. 이후 θ 갱신은 이 누적값 v에 α를 곱해 적용한다.

Recall gradient descent
θt+1=θtα[J[θt]]
where α is the step size
Gradient descent with momentum uses moving averages of gradients to update parameters
vt+1=βvt+(1β)[J[θt]]
θt+1=θtαvt+1
θ=(θ1θ2:θD)
수식
Alternatively, we write the gradient descent with momentum as
수식
When gradients keep pointing in the same direction, this will increase the size of the steps taken towards the minimum
When the gradient keeps changing direction, momentum will smooth out the variations

Manhattan-Learning Rule

기울기의 크기 대신 부호로 이동한다

Manhattan 규칙은 각 가중치의 기울기가 양수인지 음수인지에 따라 일정한 크기로 이동한다. 기울기가 크다고 이동량을 더 크게 만드는 구조가 아니다. 0인 경우의 분기도 함께 읽으면 좌표별 갱신 규칙이 명확해진다.

Acts independently on each weight
Update depend on the sign of the gradient
The update - value is constant through iterations
θit+1=θit+Δθi
where
Δθi = {{{-Δ0, if ∂J/∂θi>0}, {Δ0, if ∂J/∂θi<0}, {0, else}}
where Δ0 is the update - value, which is a problem - dependent constant

Resilent Backprop (Rprop)

Rprop은 좌표별 이동 크기를 조절한다

연속한 두 기울기의 부호가 같으면 그 좌표의 이동 크기를 늘리고, 부호가 바뀌면 줄이는 구조이다. η⁺와 η⁻는 이 증가·감소의 비율을 나타낸다. 원문은 전체 배치 맥락을 설명하므로, 미니배치에 같은 특성이 그대로 보장된다고 가정하지 않는다.

Used for full batch learning
Goal : Resolve the problem that gradients may vary widely in magnitudes
Acts independently on each weight
Extension of Manhattan learning rule
Combines the idea of using the sign of the gradient with the idea of adapting the step size individually for each weight
The update - value, Δi, for each weight evolves during the learning process
Increase the learning rate for a weight multiplicatively if signs of last two gradients agree
Else decrease learning rate multiplicatively
Initialize all updates at iteration 0 to constant value
The update - value, Δi, for each weight evolves during the learning process
수식
where 0<η <1<η+. (typical setting : η+= 1.2, η= 0.5)
Update weights : θit+1 = θit + Δθit, where
θit = {{{-Δit, if ∂J/∂θi>0}, {Δit, if ∂J/∂θi<0}, {0, else}}
Does not work well for mini - batch learning

AdaGrad: Adaptive Gradient

AdaGrad는 누적 제곱으로 보폭을 나눈다

각 매개변수에 대해 지금까지의 기울기 제곱을 모으고, 그 제곱근이 갱신식의 분모에 들어간다. 누적량이 큰 좌표는 같은 현재 기울기에서도 상대적으로 작은 이동을 하게 된다. 원문의 i 좌표와 분모 첨자 표기는 대응을 확인하며 읽는다.

A different step size for every parameter θi at every time step t .
θit+1=θitαG1,1t+ϵJ[θit]
where Gi,it = ∑_ (j = 1)^t (∇J[θij])^2 contains the sum of squares of the gradients w . r . t . θi up to time step t
Gimi^(t) represents the diagonal entries of the matrix Gt which is calculated as
Gt=diag[j=1t(J[θj])(J[θj])T]

RMSProp

RMSProp은 최근 제곱기울기에 더 비중을 둔다

모든 과거 제곱을 계속 더하는 대신 지수이동평균으로 r을 갱신한다. 현재 기울기를 √(r+ε)로 나누어 좌표별 크기를 조절한 뒤 α를 곱한다. 여기서 제곱과 나눗셈은 원문에 적힌 대로 성분별 연산이다.

RMSProp=Rprop+SGD
Adaptive individual learning rate for each weight
Instead of accumulating all past squared gradients, the moving average is used to scale the step size
Update parameters θt by
rt+1=βrt+(1β)(J[θt])2(elementwisesquare)
vt+1=J[θt]rt+1+ϵ(elementwisedivision)
θt+1=θtαvt+1

ADAM Optimization

Adam은 방향 누적과 크기 누적을 함께 사용한다

v에는 기울기를, r에는 기울기의 제곱을 누적한다. 두 누적값에 초기 편향 보정을 적용한 뒤, 보정한 v를 보정한 r의 제곱근으로 나누어 갱신한다. 분자와 분모가 서로 다른 정보를 담는다는 점이 핵심이다. 원문에 생략된 안정화 상수를 새로 넣은 식으로 설명하지는 않는다.

Uses estimations of first and second moments of gradient to adapt the learning rate for each weight of the neural network
Adaptive individual learning rate for each weight
ADAM=momentum+biascorrection+RMSProp
vt=β1vt1+(1β1)(J[θt1])
rt=β2rt1+(1β2)(J[θt1])2(elementwisesquare)
vtbc=vt1β1t
rtbc=rt1β2t
θt=θt1αvtbcrtbc(elementwisedivision)

Learning Rate Decay (Step Size)

학습이 진행되며 이동 크기를 줄인다

α₀는 처음 설정한 이동 크기이고, 이후 식은 epoch나 반복 횟수에 따라 α를 줄이는 예이다. 역수, 지수, 제곱근 형태가 각각 얼마나 빠르게 감소하는지 비교한다. 원문은 여러 선택안을 나열한 것이므로 하나의 필수 규칙으로 읽지 않는다.

Slowly reduce the step size α
1 epoch = 1 pass through whole training examples
Strategies (η = decay rate&Ω = epoch number)
α=11+ηΩα0
α=0.95Ωα0
α=kΩα0
α=ktα0
or α is manually set such that the value of constant is decreasing in a stepwise fashion

Dropout

Dropout은 학습 중 일부 성분의 통과 여부를 정한다

베르누이 변수로 만든 마스크를 중간층 값에 성분별로 곱한다. 0인 위치는 그 계산에서 제거되고 1인 위치는 남는다. 이것은 학습 중 연결을 선택하는 규칙이며, 측정 데이터가 실제로 사라졌다는 의미는 아니다.

Form a vector of independent Bernoulli random variables, Zl, where zil ~ Bern[p]
Feedforwardoperationsare:hil+1=σ[wil+1T(hlzl)+bil+1]

Normalization

평균과 퍼짐을 분리해 입력의 기준을 맞춘다

먼저 모든 x의 평균 μ를 구하고, 평균에서의 차이를 제곱해 분산을 구한다. z=(x−μ)/σ는 중심을 0으로 옮기고 퍼짐을 표준편차 기준으로 맞추는 계산이다. 모든 입력이 같은 경우처럼 σ가 0이면 이 나눗셈을 그대로 수행할 수 없다.

Standardization
X={x1,x2,,xN}
mean μ=1Nn=1Nxn
var σ2=1Nn=1N(xnμ)2
Z={z1,z2,,zN}
mean=0
variance=1
zn=xnμσ

Batch Normalization

배치 정규화는 같은 성분의 샘플들을 기준으로 한다

먼저 가중합 a를 만든 뒤 미니배치 안에서 해당 성분의 평균과 분산을 계산한다. 이를 이용해 a를 정규화하고, 학습 가능한 γ와 β로 다시 크기와 위치를 조정한다. 평균·분산은 데이터에서 계산하는 값이고 γ·β는 학습하는 값이라는 점을 구별한다.

Pre - activation is calculated as a linear sum of incoming inputs
ail=jWi,jlhjl1+bil
Activation is a non - linear transform of the pre - activation
hil=ϕ[ail]
원본 도해

BN is applied to individual dimension for each mini-batch of size M

Normalizepreactivationai
z~i=aiμiσi2+ϵ
where
μi=1Mm=1Mai,m
σi2=1Mm=1M(ai,mμi)2

Rescale and shift by learnable parameters

zi=γiz~i+βi
where (γi, βi) are learnable parameters that are learned via back - prop
원본 도해
Since the mean is subtracted, bias term bil is not necessary . In other words, simply use ail = ∑_jWi,jl hjl1

BN in Inference Phase

추론 때는 정규화의 기준 통계를 사용한다

원문은 배치에서 얻은 통계로 추론에 사용할 평균과 분산을 구성한다. 마지막 scale-and-shift 식은 정규화와 선형 조정을 하나로 정리한 형태이다. 학습 시점의 배치 통계와 추론 시점에 사용할 기준 통계를 같은 순간의 값으로 혼동하지 않는다.

Suppose that μi,B and σi,B2 are mean and variance computed using a mini - batch ℬ of size M
In inference phase, we compute
E[ai]=EB[μi,B]
var[ai]=MM1EB[σi,B2]
Scale and shift
zi=γiaivar[ai]+ϵ+(βiγE[ai]var[ai]+ϵ)

Layer Normalization

층 정규화는 통계를 모으는 축이 다르다

배치 정규화와 달리 한 층의 여러 은닉 성분을 모아 평균과 표준편차를 계산한다. 따라서 두 방법의 차이는 정규화라는 이름보다 어떤 값들을 한 집합으로 묶어 통계를 구하는지에 있다. 마지막 RNN 식에서 정규화할 가중합과 그 뒤의 활성화 함수를 나누어 읽는다.

CNN→BN
RNN→LN
Reduce the ' covariate shift ' problem by fixing the mean and the variance of the summed inputs within each layer
Compute the layer normalization statistics over all the hidden units in the same layer
μtl=1Hi=1Hai,tl
σtl=1Hi=1H(ai,tlμtl)2
LN in a RNN is performed
at=Whhht1+Whxxt
ht=ϕ[γσt1(atμt1)+b]

정리하면

각 학습법은 대체로 무엇을 누적하고, 그 값으로 이동량을 어떻게 바꾸는지가 다르다. 이름보다 갱신식에서 분자·분모·누적항의 역할을 먼저 읽는 것이 유용하다.