全连接层与 TimeDistributed 层

使用 Keras 的机器翻译

Thushan Ganegedara

Data Scientist and Author

Dense 层简介

  • 将输入向量转换为概率预测。
    • y = Weights.x + Bias

权重与偏置

使用 Keras 的机器翻译

理解 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 的机器翻译

Dense 层的输入与输出

  • Dense softmax 层
    • 接受 (batch size, input size) 数组
      • 例如:x = [[1, 6, 8], [8, 9, 10]] # a 2x3 array
    • 产生 (batch size, num classes) 数组
      • 例如:类别数 = 4
      • 例如:y = [[0.1, 0.3, 0.4, 0.2], [0.2, 0.5, 0.1, 0.2]] # a 2x4 array
    • 每个样本的输出是对各类别的概率分布
      • 按列求和为 1
    • np.argmax(y, axis=-1) 得到每个样本的类别
      • 例如:np.argmax(y,axis=-1) 得到 [2,1]
使用 Keras 的机器翻译

理解 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 的机器翻译

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 的机器翻译

按时间维切片数据

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 的机器翻译

Passons à la pratique !

使用 Keras 的机器翻译

Preparing Video For Download...