首页 > 解决方案 > LSTM 层上的时间注意力?

问题描述

我想在 LSTM 层上实现注意力。让我把详细描述:

我们分析了 LSTM 的 8 个隐藏状态,它们表示输入帧不同部分的嵌入。我们将前 7 个隐藏状态视为历史时间上下文,并学习与这些状态相对应的 7 个权重:

过去的上下文 = [h1;h2;h3;:::h8] (1)

电流 = h8 (2)

转换后的上下文 = tanh(W1 × 过去的上下文 + b1) (3)

权重 = softmax(W2 × 转换后的上下文 + b2) (4)

最终嵌入 = 过去的上下文 × 权重 + 当前 (5)

b1 和 b2 表示两个线性层中的偏差,W1 和 W2 表示线性层中的二维矩阵。我们最初应用了一个线性变换,伴随着一个 tanh 线性,将这七个大小为 128 的向量中的每一个变换为七个大小为 128 的新向量(等式 3)。另一个线性变换将这 8 个向量分别转换为大小为 1,基本上为我们提供了每个隐藏状态的分数。然后将这些分数通过 softmax 以给出最终的权重集(方程式 4)。这些权重用于计算所有 8 个隐藏状态的加权和,以给出过去上下文的最终嵌入。这个过去的上下文被添加到最后一个隐藏状态,以给出输入帧的最终嵌入(等式 5)。这个最终的嵌入用于分类。

请根据描述验证我的代码。这样对吗?

from tensorflow.keras.layers import Input, Dense, Lambda, Dot, Activation, Concatenate
from tensorflow.keras.layers import Layer
import tensorflow as tf


def attention(lstm_hidden_status):  # Tensor("lstm_1/transpose_1:0", shape=(?, 8, 128), dtype=float32)
    hidden_size = lstm_hidden_status.get_shape().as_list()  # get all dimensions all list
    hidden_size = int(hidden_size[2]) # 128
    # feed to Forward Neural Network
    h_t = Lambda(lambda x: x[:, -1, :], output_shape=(hidden_size,), name='last_hidden_state')(lstm_hidden_status) # Tensor("last_hidden_state/strided_slice:0", shape=(?, 128), dtype=float32)
    transformed_context = Dense(hidden_size, use_bias=True, activation='tanh', name='transformed_context_vec')(
        lstm_hidden_status) # Tensor("transformed_context_vec/Tanh:0", shape=(?, 8, 128), dtype=float32)

    score = Dot(axes=[1, 2], name='attention_score')([h_t, transformed_context]) # Tensor("attention_score/Squeeze:0", shape=(?, 8), dtype=float32)
    attention_weights = Dense(8, use_bias=True, activation='softmax', name='attention_weight')(score) # Tensor("attention_weight/Softmax:0", shape=(?, 8), dtype=float32)
    context_vector = Dot(axes=[1, 1], name='context_vector')([lstm_hidden_status, attention_weights]) # Tensor("context_vector/Squeeze:0", shape=(?, 128), dtype=float32)
    new_context_vector = context_vector + h_t # Tensor("add:0", shape=(?, 128), dtype=float32)
    return new_context_vector 

具体来说,我在这里很困惑score = Dot(axes=[1, 2], name='attention_score')([h_t, transformed_context]),为什么我们要使用Dot产品?所有调试输出都附在每一行上。

标签: pythontensorflowkeraslstmattention-model

解决方案


推荐阅读