簡體   English   中英

注意層如何在喀拉拉邦實現?

[英]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')
  • 哪個是值得關注的正確實施方式?
  • 第二種方法中的RepeatVectorPermute層背后的RepeatVector是什么?
  • 在第一種方法中, W1W2是權重; 為什么在這里將稠密的層視為權重?
  • 為什么將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.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM