Skip to main content

LSTM과 GRU — 게이트 메커니즘

LSTM(Long Short-Term Memory)과 GRU(Gated Recurrent Unit)는 기본 RNN의 기울기 소실 문제를 게이트 메커니즘으로 해결합니다.

핵심 아이디어

게이트(Gate)는 정보의 흐름을 제어하는 밸브 역할을 합니다. Sigmoid 함수(0~1)로 정보를 얼마나 통과시킬지 결정합니다.

LSTM

LSTM은 **셀 상태(Cell State)**라는 별도의 정보 고속도로를 유지하여 장기 기억을 보존합니다. 세 개의 게이트(망각, 입력, 출력)로 정보 흐름을 제어합니다.

수학적 표현

ft=σ(Wf[ht1,xt]+bf)(망각 게이트)f_t = \sigma(W_f [h_{t-1}, x_t] + b_f) \quad \text{(망각 게이트)} it=σ(Wi[ht1,xt]+bi)(입력 게이트)i_t = \sigma(W_i [h_{t-1}, x_t] + b_i) \quad \text{(입력 게이트)} C~t=tanh(WC[ht1,xt]+bC)(후보 셀 상태)\tilde{C}_t = \tanh(W_C [h_{t-1}, x_t] + b_C) \quad \text{(후보 셀 상태)} Ct=ftCt1+itC~t(셀 상태 업데이트)C_t = f_t \odot C_{t-1} + i_t \odot \tilde{C}_t \quad \text{(셀 상태 업데이트)} ot=σ(Wo[ht1,xt]+bo)(출력 게이트)o_t = \sigma(W_o [h_{t-1}, x_t] + b_o) \quad \text{(출력 게이트)} ht=ottanh(Ct)(은닉 상태)h_t = o_t \odot \tanh(C_t) \quad \text{(은닉 상태)}

PyTorch 구현

import torch
import torch.nn as nn

lstm = nn.LSTM(
    input_size=10,
    hidden_size=20,
    num_layers=2,       # 2층 LSTM
    batch_first=True,
    dropout=0.2,        # 층 간 Dropout
    bidirectional=False, # 양방향 여부
)

x = torch.randn(32, 15, 10)  # (배치, 시퀀스, 입력)
output, (h_n, c_n) = lstm(x)

print(f"출력: {output.shape}")       # (32, 15, 20)
print(f"은닉 상태: {h_n.shape}")     # (2, 32, 20) — 2층
print(f"셀 상태: {c_n.shape}")       # (2, 32, 20)

GRU (Gated Recurrent Unit)

GRU는 LSTM을 단순화한 버전입니다. 셀 상태를 별도로 유지하지 않고, 두 개의 게이트(리셋, 업데이트)만 사용합니다. zt=σ(Wz[ht1,xt])(업데이트 게이트)z_t = \sigma(W_z [h_{t-1}, x_t]) \quad \text{(업데이트 게이트)} rt=σ(Wr[ht1,xt])(리셋 게이트)r_t = \sigma(W_r [h_{t-1}, x_t]) \quad \text{(리셋 게이트)} h~t=tanh(W[rtht1,xt])(후보 은닉 상태)\tilde{h}_t = \tanh(W [r_t \odot h_{t-1}, x_t]) \quad \text{(후보 은닉 상태)} ht=(1zt)ht1+zth~t(은닉 상태 업데이트)h_t = (1 - z_t) \odot h_{t-1} + z_t \odot \tilde{h}_t \quad \text{(은닉 상태 업데이트)}
gru = nn.GRU(
    input_size=10,
    hidden_size=20,
    num_layers=2,
    batch_first=True,
    dropout=0.2,
)

output, h_n = gru(x)  # 셀 상태 없음
print(f"출력: {output.shape}")    # (32, 15, 20)
print(f"은닉 상태: {h_n.shape}")  # (2, 32, 20)

LSTM vs GRU 비교

특성LSTMGRU
게이트 수3 (망각, 입력, 출력)2 (리셋, 업데이트)
상태은닉 상태 + 셀 상태은닉 상태만
파라미터많음적음 (~25% 감소)
학습 속도느림빠름
장기 의존성우수우수 (LSTM과 유사)
선택 기준긴 시퀀스, 복잡한 의존성짧은 시퀀스, 빠른 학습

양방향 RNN (Bidirectional)

미래 정보도 활용하기 위해 순방향/역방향 두 개의 RNN을 결합합니다.
bilstm = nn.LSTM(
    input_size=10,
    hidden_size=20,
    num_layers=1,
    batch_first=True,
    bidirectional=True,  # 양방향
)

output, (h_n, c_n) = bilstm(x)
print(f"출력: {output.shape}")    # (32, 15, 40) — 20*2
print(f"은닉 상태: {h_n.shape}")  # (2, 32, 20) — 순방향 + 역방향
LSTM/GRU는 기본 RNN보다 장기 의존성을 잘 처리하지만, 여전히 시퀀스 길이가 수백 이상이면 성능이 저하됩니다. 또한 순차적 처리 구조로 인해 병렬화가 어려워 학습 속도가 느립니다. 이러한 한계가 Transformer의 Self-Attention 메커니즘 개발의 동기가 되었습니다.

참고 논문

논문연도핵심 기여
Long Short-Term Memory (Hochreiter & Schmidhuber)1997LSTM 제안
Learning Phrase Representations using RNN Encoder-Decoder (Cho et al.)2014GRU 제안
LSTM: A Search Space Odyssey (Greff et al.)2017LSTM 변형 비교 분석