LSTM와 GRU 셀

PyTorch로 배우는 Intermediate Deep Learning

Michal Oleszak

Machine Learning Engineer

단기 메모리 문제

  • RNN 셀은 숨김 상태로 메모리를 유지합니다
  • 이 메모리는 매우 단기적입니다
  • 더 강력한 두 셀이 해결합니다:
    • LSTM (Long Short-Term Memory) 셀
    • GRU (Gated Recurrent Unit) 셀

순환 뉴런의 도식. 시간 단계 2에서 입력 h2와 x2를 받고, 출력 y2와 h3를 생성합니다.

PyTorch로 배우는 Intermediate Deep Learning

RNN 셀

RNN 셀의 도식.

  • 입력 2개:
    • 현재 입력 x
    • 이전 숨김 상태 h
  • 출력 2개:
    • 현재 출력 y
    • 다음 숨김 상태 h
PyTorch로 배우는 Intermediate Deep Learning

LSTM 셀

LSTM 셀의 도식.

  • 출력 hy는 동일합니다
  • 입력과 출력 3개(숨김 상태 2개):

    • h: 단기 상태
    • c: 장기 상태
  • 3개의 "게이트":

    • 망각 게이트: 장기 메모리에서 제거할 항목
    • 입력 게이트: 장기 메모리에 저장할 항목
    • 출력 게이트: 현재 시점에 반환할 항목
PyTorch로 배우는 Intermediate Deep Learning

PyTorch의 LSTM

class Net(nn.Module):
    def __init__(self, input_size):
        super().__init__()

self.lstm = nn.LSTM( input_size=1, hidden_size=32, num_layers=2, batch_first=True, ) self.fc = nn.Linear(32, 1)
def forward(self, x): h0 = torch.zeros(2, x.size(0), 32) c0 = torch.zeros(2, x.size(0), 32)
out, _ = self.lstm(x, (h0, c0))
out = self.fc(out[:, -1, :]) return out
  • __init__():
    • nn.RNNnn.LSTM으로 교체
  • forward():
    • 추가 숨김 상태 c를 사용
    • ch를 0으로 초기화
    • 두 숨김 상태를 lstm 레이어에 전달
PyTorch로 배우는 Intermediate Deep Learning

GRU 셀

GRU 셀의 도식.

  • LSTM 셀의 단순화 버전
  • 숨김 상태 1개만 사용
  • 출력 게이트 없음
PyTorch로 배우는 Intermediate Deep Learning

PyTorch의 GRU

class Net(nn.Module):
    def __init__(self, input_size):
        super().__init__()

self.gru = nn.GRU( input_size=1, hidden_size=32, num_layers=2, batch_first=True, ) self.fc = nn.Linear(32, 1)
def forward(self, x): h0 = torch.zeros(2, x.size(0), 32) out, _ = self.gru(x, h0) out = self.fc(out[:, -1, :]) return out
  • __init__():
    • nn.RNNnn.GRU로 교체
  • forward():
    • gru 레이어 사용
PyTorch로 배우는 Intermediate Deep Learning

RNN, LSTM, GRU 중 무엇을 쓸까요?

  • RNN은 현재 거의 사용되지 않음
  • GRU는 LSTM보다 단순 → 연산량 적음
  • 성능은 용도에 따라 다름
  • 둘 다 시도해 비교하세요

LSTM과 GRU 셀의 도식.

PyTorch로 배우는 Intermediate Deep Learning

연습해 봅시다!

PyTorch로 배우는 Intermediate Deep Learning

Preparing Video For Download...