Dense 層と TimeDistributed 層

Kerasで学ぶMachine Translation

Thushan Ganegedara

Data Scientist and Author

Dense 層の概要

  • 入力ベクトルを確率予測に変換
    • y = Weights.x + Bias

重みとバイアス

Kerasで学ぶMachine Translation

Dense 層を理解する

Dense 層の定義と使用

dense = Dense(3, activation='softmax')
inp = Input(shape=(3,))
pred = dense(inp)
model = Model(inputs=inp, outputs=pred)

カスタム初期化での Dense 層

from tensorflow.keras.initializers import RandomNormal
init = RandomNormal(mean=0.0, stddev=0.05, seed=6000)
dense = Dense(3, activation='softmax', 
             kernel_initializer=init, bias_initializer=init)
Kerasで学ぶMachine Translation

Dense 層の入出力

  • Dense + softmax 層
    • 入力: (batch size, input size) 配列
      • x = [[1, 6, 8], [8, 9, 10]] # 2x3 配列
    • 出力: (batch size, num classes) 配列
      • 例 クラス数 = 4
      • y = [[0.1, 0.3, 0.4, 0.2], [0.2, 0.5, 0.1, 0.2]] # 2x4 配列
    • 各サンプルの出力はクラス上の確率分布
      • 列方向に合計が 1
    • クラスは np.argmax(y, axis=-1) で取得
      • np.argmax(y,axis=-1)[2,1]
Kerasで学ぶMachine Translation

TimeDistributed 層を理解する

  • Dense を時系列入力に適用可能
dense_time = TimeDistributed(Dense(3, activation='softmax'))
inp = Input(shape=(2, 3))
pred = dense_time(inp)
model = Model(inputs=inp, outputs=pred)
Kerasで学ぶMachine Translation

TimeDistributed 層の入出力

  • 入力: (batch size, sequence length, input size) 配列
x = [[[1, 6], [8, 2], [1, 2]], 
    [[8, 9], [10, 8], [1, 0]]] # a 2x3x2 array
  • 出力: (batch size, sequence length, num classes) 配列
    • 例 クラス数 = 3
y = [[[0.1, 0.5, 0.4], [0.8, 0.1, 0.1], [0.6, 0.2, 0.2]], 
     [[0.2, 0.5, 0.3], [0.2, 0.5, 0.3], [0.2, 0.8, 0.0]]] # a 2x3x3 array
  • 各サンプルの出力はクラス上の確率分布
  • クラスは np.argmax(y, axis=-1) で取得
Kerasで学ぶMachine Translation

時間次元でのスライス

y = [[[0.1, 0.5, 0.4], [0.8, 0.1, 0.1], [0.6, 0.2, 0.2]], 
     [[0.2, 0.5, 0.3], [0.2, 0.5, 0.3], [0.2, 0.8, 0.0]]] # a 2x3x3 array
classes = np.argmax(y, axis=-1) # a 2 x 3 array

時間方向に沿ってデータを反復処理

for t in range(3):
  # Get the t-th time-dimension slice of y and classes
  for prob, c in zip(y[:,t,:], classes[:,t]):
     print("Prob: ", prob, ", Class: ", c)
Prob:  [0.1 0.5 0.4] , Class:  1
Prob:  [0.2 0.5 0.3] , Class:  1
Prob:  [0.8 0.1 0.1] , Class:  0
...
Kerasで学ぶMachine Translation

実践しましょう!

Kerasで学ぶMachine Translation

Preparing Video For Download...