循環神經網路

Intermediate Deep Learning with PyTorch

Michal Oleszak

Machine Learning Engineer

循環神經元

  • 前饋式網路
  • RNN:含回饋連結
  • 循環神經元:
    • 輸入 x
    • 輸出 y
    • 隱藏狀態 h
  • 在 PyTorch 中:nn.RNN()

一般 RNN 神經元示意圖:神經元套用權重與活化函式,接收輸入 x,產生輸出 y 與 h,其中 h 會回饋至自身。

Intermediate Deep Learning with PyTorch

沿時間展開的循環神經元

循環神經元示意。時間步 0:接收輸入 h0 與 x0,輸出 y0 與 h1。

Intermediate Deep Learning with PyTorch

沿時間展開的循環神經元

循環神經元示意。時間步 1:接收輸入 h1 與 x1,輸出 y1。

Intermediate Deep Learning with PyTorch

沿時間展開的循環神經元

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

Intermediate Deep Learning with PyTorch

深層 RNN

兩個循環神經元構成一層的示意圖。每個時間步,輸出 y 傳遞到下一個神經元。

Intermediate Deep Learning with PyTorch

序列對序列架構

  • 輸入序列,使用整段輸出序列
  • 範例:即時語音辨識

架構示意:每個時間步都有新輸入,且每個時間步產生的輸出 y 皆以綠色標示為已使用。

Intermediate Deep Learning with PyTorch

序列對向量架構

  • 輸入序列,只使用最後一個輸出
  • 範例:文字主題分類

架構示意:每個時間步都有新輸入,但僅最後時間步的輸出 y 以綠色標示為已使用。

Intermediate Deep Learning with PyTorch

向量對序列架構

  • 輸入單一向量,使用整段輸出序列
  • 範例:文字生成

架構示意:只有第一個時間步有輸入,其後每個時間步產生的輸出 y 皆以綠色標示為已使用。

Intermediate Deep Learning with PyTorch

編碼器-解碼器架構

  • 先輸入完整序列,再開始使用輸出序列
  • 範例:機器翻譯

架構示意:前半段(編碼器)每個時間步接收輸入但忽略輸出;後半段(解碼器)不再接收輸入,但使用每個時間步的所有輸出。

Intermediate Deep Learning with PyTorch

PyTorch 中的 RNN

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

self.rnn = nn.RNN( 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.rnn(x, h0)
out = self.fc(out[:, -1, :]) return out
  • __init__ 方法定義模型類別
  • 定義循環層 self.rnn
  • 定義線性層 fc
  • forward() 中,將初始隱藏狀態設為全零
  • 將輸入與初始隱藏狀態送入 RNN 層
  • 取最後時間步的 RNN 輸出,再送入線性層
Intermediate Deep Learning with PyTorch

一起來練習吧!

Intermediate Deep Learning with PyTorch

Preparing Video For Download...