L2 regularization과 weight decay

2024. 8. 19. 03:46머신러닝&딥러닝/인공신경망 기초

728x90

 
 
보편 근사 정리 (Universal Approximation Theorem)에 따르면, 파라미터 수가 충분한 인공신경망은 임의의 연속적인 다변수함수를 원하는 정확도로 근사할 수 있다. 즉, 파라미터 수가 충분하다면, 이론상 train set의 accuracy를 100%으로 만드는 파라미터 조합은 반드시 존재한다. https://en.wikipedia.org/wiki/Universal_approximation_theorem

 

Universal approximation theorem - Wikipedia

From Wikipedia, the free encyclopedia Feed-forward neural network with a 1 hidden layer can approximate continuous functions In the mathematical theory of artificial neural networks, universal approximation theorems are theorems[1][2] of the following form

en.wikipedia.org

 
 
하지만, 실제 모델에서 우리는 이러한 상황을 원하지 않는다. 이것이 바로 딥러닝에서 흔히 말하는 오버피팅(overfitting)이기 때문이다. 좋은 모델은 적절한 decision boundary를 찾아 validation 및 test set에서도 좋은 성능을 보여야 한다.

 


Train set에 대한 loss를 0으로 만드는 파라미터 조합을 $W = w_1, w_2, ..., w_k$라고 했을 때, 모델이 완전히 이 값으로 수렴하지 않도록 regularization을 걸 수 있다. 
 

Norm

 
$N$차원 공간에 대하여, 아래와 같은 식을 p-norm이라고 정의한다.

아래는 python으로 3차원에서의 p-norm을 간단히 시각화한 코드이다.

import numpy as np
import matplotlib.pyplot as plt
from mpl_toolkits.mplot3d import Axes3D
from ipywidgets import interact, FloatSlider

def plot_pn_space(p):
    fig = plt.figure()
    ax = fig.add_subplot(111, projection='3d')

    u = np.linspace(0, 2 * np.pi, 100)
    v = np.linspace(0, np.pi, 100)
    u, v = np.meshgrid(u, v)
    x = np.abs(np.sin(v) * np.cos(u))**p
    y = np.abs(np.sin(v) * np.sin(u))**p
    z = np.abs(np.cos(v))**p

    norm = (x**p + y**p + z**p)**(1/p)
    x /= norm
    y /= norm
    z /= norm

    ax.plot_surface(x, y, z, rstride=5, cstride=5, color='y', alpha=0.5)

    ax.set_xlabel('X')
    ax.set_ylabel('Y')
    ax.set_zlabel('Z')
    ax.set_title(f'3D p-norm Space with p = {p:.1f}')

    plt.show()

interact(plot_pn_space, p=FloatSlider(value=2.0, min=0.1, max=3.0, step=0.1, description='p:'))

 

 
p=1일 때는 완전한 평면, p=2일 때는 구를 이루는 것을 확인할 수 있다. 실제로 $ \| \mathbf{x} \|_1 = \sum_{i=1}^{n} |x_i|$은 n차원에서 hyperplane을, $ \| \mathbf{x} \|_2 = \left( \sum_{i=1}^{n} |x_i|^2 \right)^{\frac{1}{2}} $은 n차원에서 hypersphere의 식이다.
 

L1 regularization, L2 regularization

 
L1, L2 regularization은 모델의 과적합을 방지하기 위해 loss function에 가중치 벡터의 L1, L2 norm을 추가하는 방식이다. 일반적인 loss function을 $\mathcal{L}(\mathbf{w})$라고 할 때, L1 regularization을 적용한 loss function은 아래와 같이 바뀐다.
$$ \mathcal{L}_{\text{reg}}(\mathbf{w}) = \mathcal{L}(\mathbf{w}) + \lambda \|\mathbf{w}\|_1 $$
또한 L2 regularization을 적용한 것은 아래와 같이 바뀐다.
$$ \mathcal{L}_{\text{reg}}(\mathbf{w}) = \mathcal{L}(\mathbf{w}) + \frac{\lambda}{2} \|\mathbf{w}\|_2^2 $$
 
L2 regularization 식을 특정 파라미터 $\mathbf{w}_{\text{old}}$로 미분하면 식이 
$$ \mathbf{w}_{\text{new}} = \mathbf{w}_{\text{old}} - \eta \left( \nabla \mathcal{L}(\mathbf{w}_{\text{old}}) + \lambda \mathbf{w}_{\text{old}} \right) $$
와 같이 변하는데, 매 iteration마다 $\lambda$에 비례해서 weight를 떨어뜨리는 효과가 있다. 이러한 L2 regularization의 효과를 weight decay라고 부른다.
 

L2 norm과 weight decay의 관계

 
train loss를 0으로 만드는 파라미터 해는 n차원 공간 어딘가에 존재한다. 그러나, 이 값은 원점 (모든 파라미터가 0인 경우)에서 매우 멀리 떨어져 있을수도 있다. L2 regularization의 효과는, loss에 이 L2-norm을 추가하여 학습 과정에서 파라미터가 해에 가까워지긴 하지만, 너무 크지 않은 값을 유지하면서 접근하도록 하는 효과가 있다. 따라서, L2 정규화는 모델이 입력 데이터의 노이즈나 불필요한 패턴을 학습하여 overfitting되지 않도록 도와 주어 일반화 가능한 모델을 만들 수 있도록 한다.
 
그런데 왜 L1 norm은 weight decay에 쓰지 않을까? L1 regularization을 사용하면 일부 파라미터가 0이 되어버릴 수도 있기 때문이다. 우리가 원하는 것은 모든 파라미터를 일정한 비율로 동시에 점진적으로 줄이는 것이기 때문에, weight decay에는 L2 regularization이 쓰이는 것이다.

반응형