逐次モデルを理解する

Kerasで学ぶMachine Translation

Thushan Ganegedara

Data Scientist and Author

時系列入力と逐次モデル

  • 文は時系列入力である
    • 現在の単語は前の単語に影響される
    • 例: He went to the pool for a ....
  • エンコーダ/デコーダは機械学習モデルを用いる
    • 時系列から学習できるモデル
    • これらを逐次モデルという
Kerasで学ぶMachine Translation

逐次モデル

  • 逐次モデル
    • 入力を順に処理し、各時刻で出力を生成

逐次モデルのアーキテクチャ

Kerasで学ぶMachine Translation

逐次モデルとしてのエンコーダ

  • GRU(Gated Recurrent Unit)

ゲート付き再帰ユニット

Kerasで学ぶMachine Translation

GRUレイヤーの導入

時間ステップ1で、GRUレイヤーは

  • 入力「We」を取り込む
  • 初期状態 (0,0) を取り込む
  • 新しい状態 (0.8, 0.3) を出力する

GRU 1

Kerasで学ぶMachine Translation

GRUレイヤーの導入

時間ステップ2で、GRUレイヤーは

  • 入力「like」を取り込む
  • 初期状態 (0.8,0.3) を取り込む
  • 新しい状態 (0.5, 0.9) を出力する

隠れ状態は、モデルが見た内容の「記憶」を表す

GRU 2

Kerasで学ぶMachine Translation

Keras(Functional API)復習

  • Kerasには重要なオブジェクトが2つある: LayerModel
  • 入力レイヤー
    • inp = keras.layers.Input(shape=(...))
  • 隠れレイヤー
    • layer = keras.layers.GRU(...)
  • 出力
    • out = layer(inp)
  • モデル
    • model = Model(inputs=inp, outputs=out)
Kerasで学ぶMachine Translation

データ形状の理解

  • 時系列データは3次元
    • バッチ次元(例: 文のグループ)
    • 時間次元(系列長)
    • 入力次元(例: ワンホット長)
  • GRUの入力形状
    • (Batch, Time, Input)
    • (バッチサイズ, 系列長, ワンホット長)

入力データ

Kerasで学ぶMachine Translation

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で学ぶMachine Translation

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で学ぶMachine Translation

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で学ぶMachine Translation

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で学ぶMachine Translation

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で学ぶMachine Translation

Ayo berlatih!

Kerasで学ぶMachine Translation

Preparing Video For Download...