![](/img/trans.png)
[英]Attention in Keras : How to add different attention mechanism in keras Dense layer?
[英]How is attention layer implemented in keras?
我正在學習注意力模型及其在keras中的實現。 在搜索時,我首先遇到了這兩種方法, 第二種方法可用來在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
層背后的RepeatVector
是什么? W1
, W2
是權重; 為什么在這里將稠密的層視為權重? V
值視為單個單位致密層? V(score)
做什么的? 哪個是值得關注的正確實施方式?
我建議以下內容:
https://github.com/tensorflow/models/blob/master/official/transformer/model/attention_layer.py#L24
上面的多標題Attention層實現了一個巧妙的技巧:調整矩陣的形狀,以便將其成形為(batch_size,heads,time_steps,features / heads)而不是成形為(batch_size,heads,time_steps,features / heads),然后執行對“功能/標題”塊的計算。
第二種方法中的RepeatVector和Permute層背后的直覺是什么?
您的代碼不完整...代碼中缺少矩陣乘法(您沒有顯示正在使用的Attention層)。 這可能會修改結果的形狀,並且此代碼試圖以某種方式恢復正確的形狀。 這可能不是最好的方法。
在第一種方法中,W1,W2是權重; 為什么在這里將稠密的層視為權重?
密集層是一組權重...您的問題有點含糊。
為什么將V值視為單個單位致密層?
這是一個非常奇怪的選擇,與我對本文的閱讀或我所看到的實現都不相符。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.