기울기 소실 및 폭발

PyTorch로 배우는 Intermediate Deep Learning

Michal Oleszak

Machine Learning Engineer

기울기 소실

  • 역전파 시 기울기가 점점 작아짐
  • 앞쪽 레이어의 파라미터 업데이트가 미미
  • 모델이 학습되지 않음

레이어 인덱스에 따른 기울기 크기 그래프: 앞쪽 레이어일수록 기울기가 작음

PyTorch로 배우는 Intermediate Deep Learning

기울기 폭발

  • 기울기가 점점 커짐
  • 파라미터 업데이트 폭이 지나치게 큼
  • 학습이 발산

레이어 인덱스에 따른 기울기 크기 그래프: 앞쪽 레이어일수록 기울기가 큼

PyTorch로 배우는 Intermediate Deep Learning

불안정한 기울기의 해결 방법

  1. 적절한 가중치 초기화
  2. 적합한 활성화 함수
  3. 배치 정규화

 

 

세 가지 단계

PyTorch로 배우는 Intermediate Deep Learning

가중치 초기화

layer = nn.Linear(8, 1)
print(layer.weight)
Parameter containing:
tensor([[-0.0195,  0.0992,  0.0391,  0.0212,
         -0.3386, -0.1892, -0.3170,  0.2148]])
PyTorch로 배우는 Intermediate Deep Learning

가중치 초기화

올바른 초기화 보장:

  • 레이어 입력과 출력의 분산이 동일
  • 레이어 전후 기울기 분산이 동일

 

활성화 함수에 따른 초기화 방법:

  • ReLU 등에는 He/Kaiming 초기화 사용
PyTorch로 배우는 Intermediate Deep Learning

가중치 초기화

import torch.nn.init as init

init.kaiming_uniform_(layer.weight)
print(layer.weight)
Parameter containing:
tensor([[-0.3063, -0.2410,  0.0588,  0.2664,
          0.0502, -0.0136,  0.2274,  0.0901]])
PyTorch로 배우는 Intermediate Deep Learning

He / Kaiming 초기화

init.kaiming_uniform_(self.fc1.weight)
init.kaiming_uniform_(self.fc2.weight)
init.kaiming_uniform_(
  self.fc3.weight,
  nonlinearity="sigmoid",
)
PyTorch로 배우는 Intermediate Deep Learning

He / Kaiming 초기화

import torch.nn as nn
import torch.nn.init as init

class Net(nn.Module):
    def __init__(self):
        super().__init__()
        self.fc1 = nn.Linear(9, 16)
        self.fc2 = nn.Linear(16, 8)
        self.fc3 = nn.Linear(8, 1)


init.kaiming_uniform_(self.fc1.weight) init.kaiming_uniform_(self.fc2.weight) init.kaiming_uniform_( self.fc3.weight, nonlinearity="sigmoid", )




    def forward(self, x):
        x = nn.functional.relu(self.fc1(x))
        x = nn.functional.relu(self.fc2(x))
        x = nn.functional.sigmoid(self.fc3(x))
        return x







PyTorch로 배우는 Intermediate Deep Learning

활성화 함수

ReLU 함수 그래프: 0 이하에서는 수평선, 0 초과에서는 양의 기울기를 가짐

  • 기본 활성화 함수로 자주 사용
  • nn.functional.relu()
  • 음수 입력에서 0 출력 — 뉴런 소멸 문제

ELU 함수 그래프: ReLU와 유사하지만 음수 영역에서 부드럽게 전환됨

  • nn.functional.elu()
  • 음수 값에서도 기울기 존재 — 뉴런 소멸 방지
  • 평균 출력이 0에 근접 — 기울기 소실 방지
PyTorch로 배우는 Intermediate Deep Learning

배치 정규화

레이어 이후:

  1. 레이어 출력 정규화:

    • 평균 빼기
    • 표준 편차로 나누기
  2. 학습된 파라미터로 정규화된 출력 스케일 및 이동

모델이 각 레이어의 최적 입력 분포를 학습:

  • 손실 감소 속도 향상
  • 불안정한 기울기 방지
PyTorch로 배우는 Intermediate Deep Learning

배치 정규화

class Net(nn.Module):
    def __init__(self):
        super().__init__()
        self.fc1 = nn.Linear(9, 16)
        self.bn1 = nn.BatchNorm1d(16)

        ...


def forward(self, x): x = self.fc1(x) x = self.bn1(x) x = nn.functional.elu(x) ...
PyTorch로 배우는 Intermediate Deep Learning

연습해 봅시다!

PyTorch로 배우는 Intermediate Deep Learning

Preparing Video For Download...