gpt4 book ai didi

python - 在 Keras 中实现注意力机制

转载 作者:行者123 更新时间:2023-11-30 09:04:49 26 4
gpt4 key购买 nike

我正在尝试通过简单的 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)

'Got inputs shapes: %s' % (input_shape)) ValueError: A Concatenate layer requires inputs with matching shapes except for the concat axis. Got inputs shapes: [(None, 64), (16, 1)]

实现非常简单,只需取 lstm 输出与隐藏状态的点积,并将其用作权重函数来计算隐藏状态本身。

如何解决该错误?特别是如何让注意力概念发挥作用?

最佳答案

您可以在连接之前添加 Reshape 图层以确保兼容性。请参阅 keras 文档 here 。可能最好 reshape model_2 输出 (None, 64)

编辑:

本质上,您需要在连接之前添加具有目标形状的 reshape 图层:

model_2 = Reshape(new_shape)(model_2)

这将返回(batch_size, (new_shape))您当然可以仅使用 model_2 输出来 reshape 网络的任一分支,因为它是一个更简单的示例

话虽如此,也许值得重新考虑您的网络结构。特别是,这个问题源于第二个点层(它只提供 16 个标量)。因此,很难 reshape 形状以使两个分支匹配。

在不知道模型试图预测什么或训练数据是什么样子的情况下,很难评论两个点是否必要,但潜在的重构将解决这个问题。

关于python - 在 Keras 中实现注意力机制,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55165008/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com