簡體   English   中英

在 Keras 中實現注意力機制

[英]Implementing Attention in Keras

我試圖通過一個簡單的 lstm 在 keras 中實現注意力:

model_2_input = Input(shape=(500,))
#model_2 = Conv1D(100, 10, activation='relu')(model_2_input)
model_2 = Dense(64, activation='sigmoid')(model_2_input)
model_2 = Dense(64, activation='sigmoid')(model_2)

model_1_input = Input(shape=(None, 2048))
model_1 = LSTM(64, dropout_U = 0.2, dropout_W = 0.2, return_sequences=True)(model_1_input)
model_1, state_h, state_c = LSTM(16, dropout_U = 0.2, dropout_W = 0.2, return_sequences=True, return_state=True)(model_1) # dropout_U = 0.2, dropout_W = 0.2,


#print(state_c.shape)
match = dot([model_1, state_h], axes=(0, 0))
match = Activation('softmax')(match)
match = dot([match, state_h], axes=(0, 0))
print(match.shape)

merged = concatenate([model_2, match], axis=1)
print(merged.shape)
merged = Dense(4, activation='softmax')(merged)
print(merged.shape)
model = Model(inputs=[model_2_input , model_1_input], outputs=merged)
adam = Adam()
model.compile(loss='categorical_crossentropy', optimizer=adam, metrics=['accuracy'])

我收到了以下錯誤:

merged = concatenate([model_2, match], axis=1)

'得到輸入形狀:%s' % (input_shape)) ValueError: Concatenate層要求輸入具有匹配的形狀( Concatenate軸除外)。 得到輸入形狀:[(None, 64), (16, 1)]

實現非常簡單,只需取 lstm 輸出和隱藏狀態的點積,並將其用作權重函數來計算隱藏狀態本身。

如何解決錯誤? 特別是如何讓注意力概念發揮作用?

您可以在連接之前添加一個 Reshape 圖層以確保兼容性。 請參閱此處的keras 文檔。 可能最好重塑 model_2 輸出(None, 64)

編輯:

本質上,您需要在連接之前添加具有目標形狀的 Reshape 圖層:

model_2 = Reshape(new_shape)(model_2)

這將返回(batch_size, (new_shape))您當然可以重塑網絡的任一分支,只需使用 model_2 輸出,因為它是一個更簡單的示例

話雖如此,也許值得重新考慮您的網絡結構。 特別是,這個問題源於第二個點層(它只給你 16 個標量)。 因此,很難重塑以使兩個分支匹配。

在不知道模型試圖預測什么或訓練數據是什么樣的情況下,很難評論兩個點是否必要,但潛在的重組將解決這個問題。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

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