認識循序模型

使用 Keras 進行機器翻譯

Thushan Ganegedara

Data Scientist and Author

時間序列輸入與循序模型

  • 句子是時間序列輸入
    • 當前詞會受前面詞影響
    • 例如:He went to the pool for a ....
  • 編碼器/解碼器使用機器學習模型
    • 能從時間序列輸入學習的模型
    • 稱為 循序模型
使用 Keras 進行機器翻譯

循序模型

  • 循序模型
    • 逐步讀取輸入,在每個時間步產生輸出

循序模型架構

使用 Keras 進行機器翻譯

編碼器作為循序模型

  • GRU - 閘控式遞迴單元(Gated Recurrent Unit)

閘控式遞迴單元

使用 Keras 進行機器翻譯

GRU 層介紹

在時間步 1,GRU 層:

  • 讀入輸入「We」
  • 讀入初始狀態 (0,0)
  • 輸出新狀態 (0.8, 0.3)

GRU 1

使用 Keras 進行機器翻譯

GRU 層介紹

在時間步 2,GRU 層:

  • 讀入輸入「like」
  • 讀入狀態 (0.8,0.3)
  • 輸出新狀態 (0.5, 0.9)

隱藏狀態代表模型的「記憶」

GRU 2

使用 Keras 進行機器翻譯

Keras(Functional API)複習

  • Keras 有兩個重要物件:Layer 與 Model。
  • 輸入層
    • inp = keras.layers.Input(shape=(...))
  • 隱藏層
    • layer = keras.layers.GRU(...)
  • 輸出
    • out = layer(inp)
  • 模型
    • model = Model(inputs=inp, outputs=out)
使用 Keras 進行機器翻譯

理解資料形狀

  • 循序資料是 3 維
    • 批次維度(例如 batch = 句子群組)
    • 時間維度-序列長度
    • 輸入維度(例如 onehot 向量長度)
  • GRU 模型輸入形狀
    • (Batch, Time, Input)
    • (batch size, sequence length, onehot length)

輸入資料

使用 Keras 進行機器翻譯

用 Keras 實作 GRU

定義 Keras 層

inp = keras.layers.Input(batch_shape=(2,3,4))
gru_out = keras.layers.GRU(10)(inp)

定義 Keras 模型

model = keras.models.Model(inputs=inp, outputs=gru_out)
使用 Keras 進行機器翻譯

用 Keras 實作 GRU

用 Keras 模型做預測

x = np.random.normal(size=(2,3,4))
y = model.predict(x)
print("shape (y) =", y.shape, "\ny = \n", y)
shape (y) = (2, 10) 
y = 
[[ 0.2576233   0.01215531  ... -0.32517594  0.4483121 ],
 [ 0.54189587 -0.63834655  ... -0.4339783   0.4043917 ]]
使用 Keras 進行機器翻譯

用 Keras 實作 GRU

批次可含任意樣本數的 GRU

inp = keras.layers.Input(shape=(3,4))
gru_out = keras.layers.GRU(10)(inp)
model = keras.models.Model(inputs=inp, outputs=gru_out)
x = np.random.normal(size=(5,3,4))
y = model.predict(x)
print("y = \n", y)
y = 
 [[-1.3941444e-02 -3.3123985e-02 ... 6.5081201e-02  1.1245312e-01]
 [ 1.1409521e-03  3.6983326e-01 ... -3.4610277e-01 -3.4792548e-01]
 [ 2.5911796e-01 -3.9517123e-01 ... 5.8505309e-01  3.6908010e-01]
 [-2.8727052e-01 -5.1150680e-02 ... -1.9637148e-01 -1.5587148e-01]
 [ 3.1303680e-01  2.3338445e-01 ... 9.1499090e-04 -2.0590121e-01]]
使用 Keras 進行機器翻譯

GRU 層的 return_state 參數

inp = keras.layers.Input(batch_shape=(2,3,4))
gru_out2, gru_state = keras.layers.GRU(10, return_state=True)(inp)
print("gru_out2.shape = ", gru_out2.shape)
print("gru_state.shape = ", gru_state.shape)
gru_out2.shape =  (2, 10)
gru_state.shape =  (2, 10)

GRU return_state

使用 Keras 進行機器翻譯

GRU 層的 return_sequences 參數

inp = keras.layers.Input(batch_shape=(2,3,4))
gru_out3 = keras.layers.GRU(10, return_sequences=True)(inp)
print("gru_out3.shape = ", gru_out2.shape)
gru_out3.shape =  (2, 3, 10)

GRU return_sequences

使用 Keras 進行機器翻譯

一起來練習吧!

使用 Keras 進行機器翻譯

Preparing Video For Download...