【发布时间】:2019-07-11 10:27:58
【问题描述】:
我正在学习注意力模型及其在 keras 中的实现。在搜索时,我遇到了first 和 second 这两种方法,我们可以使用它们在 keras 中创建注意力层
# First method
class Attention(tf.keras.Model):
def __init__(self, units):
super(Attention, self).__init__()
self.W1 = tf.keras.layers.Dense(units)
self.W2 = tf.keras.layers.Dense(units)
self.V = tf.keras.layers.Dense(1)
def call(self, features, hidden):
hidden_with_time_axis = tf.expand_dims(hidden, 1)
score = tf.nn.tanh(self.W1(features) + self.W2(hidden_with_time_axis))
attention_weights = tf.nn.softmax(self.V(score), axis=1)
context_vector = attention_weights * features
context_vector = tf.reduce_sum(context_vector, axis=1)
return context_vector, attention_weights
# Second method
activations = LSTM(units, return_sequences=True)(embedded)
# compute importance for each step
attention = Dense(1, activation='tanh')(activations)
attention = Flatten()(attention)
attention = Activation('softmax')(attention)
attention = RepeatVector(units)(attention)
attention = Permute([2, 1])(attention)
sent_representation = merge([activations, attention], mode='mul')
如果我们看第一种方法,它在某种程度上是注意力数学的直接实现,而第二种方法在互联网上的点击次数更多。
我真正怀疑的是第二种方法中的这些行
attention = RepeatVector(units)(attention)
attention = Permute([2, 1])(attention)
sent_representation = merge([activations, attention], mode='mul')
- 哪个是引起注意的正确实施方式?
- 第二种方法中
RepeatVector和Permute层背后的直觉是什么? - 在第一种方法中
W1,W2是权重;为什么在这里将密集层视为权重? - 为什么
V值被视为单个单元密集层? -
V(score)是做什么的?
【问题讨论】:
标签: python keras deep-learning tf.keras attention-model