LSTM 與 GRU 單元

Intermediate Deep Learning with PyTorch

Michal Oleszak

Machine Learning Engineer

短期記憶問題

  • RNN 單元透過隱藏狀態維持記憶
  • 但記憶僅短期
  • 兩種更強的單元可解決:
    • LSTM(Long Short-Term Memory)單元
    • GRU(Gated Recurrent Unit)單元

循環神經元示意圖。時間步 2 接收輸入 h2 與 x2,輸出 y2 與 h3。

Intermediate Deep Learning with PyTorch

RNN 單元

RNN 單元示意圖。

  • 兩個輸入:
    • 當前輸入資料 x
    • 前一個隱藏狀態 h
  • 兩個輸出:
    • 當前輸出 y
    • 下一個隱藏狀態 h
Intermediate Deep Learning with PyTorch

LSTM 單元

LSTM 單元示意圖。

  • 輸出 hy 相同
  • 三個輸入與輸出(兩個隱藏狀態):

    • h:短期狀態
    • c:長期狀態
  • 三個「閘」:

    • 遺忘閘:從長期記憶移除什麼
    • 輸入閘:長期記憶要儲存什麼
    • 輸出閘:當前時間步要輸出什麼
Intermediate Deep Learning with PyTorch

在 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.RNN 換成 nn.LSTM
  • forward():
    • 新增另一個隱藏狀態 c
    • 以零初始化 ch
    • 將兩個隱藏狀態一併傳入 lstm
Intermediate Deep Learning with PyTorch

GRU 單元

GRU 單元示意圖。

  • LSTM 的精簡版
  • 僅一個隱藏狀態
  • 沒有輸出閘
Intermediate Deep Learning with PyTorch

在 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.RNN 換成 nn.GRU
  • forward():
    • 使用 gru
Intermediate Deep Learning with PyTorch

該用 RNN、LSTM,還是 GRU?

  • RNN 現在較少使用
  • GRU 較 LSTM 簡單=計算較少
  • 相對效能依情境而異
  • 兩者都試試並比較

LSTM 與 GRU 單元示意圖。

Intermediate Deep Learning with PyTorch

一起來練習吧!

Intermediate Deep Learning with PyTorch

Preparing Video For Download...