当前位置:   article > 正文

pytorch实现LSTM+Attention文本分类_pytorch实现bilstm+attention

pytorch实现bilstm+attention

直接看模型部分代码。

class BiLSTM_Attention(nn.Module):
    def __init__(self, vocab_size, embedding_dim, num_hiddens, num_layers):
        super(BiLSTM_Attention, self).__init__()
        # embedding之后的shape: torch.Size([200, 8, 300])
        self.word_embeddings = nn.Embedding(vocab_size, embedding_dim)
        self.word_embeddings = self.word_embeddings.from_pretrained(
            vectors, freeze=False)
        # bidirectional设为True即得到双向循环神经网络
        self.encoder = nn.LSTM(input_size=embedding_dim,
                               hidden_size=num_hiddens,
                               num_layers=num_layers,
                               batch_first=False,
                               bidirectional=True)
        # 初始时间步和最终时间步的隐藏状态作为全连接层输入
        self.w_omega = nn.Parameter(torch.Tensor(
            num_hiddens * 2, num_hiddens * 2))
        self.u_omega = nn.Parameter(torch.Tensor(num_hiddens * 2, 1))
        self.decoder = nn.Linear(2*num_hiddens, 2)

        nn.init.uniform_(self.w_omega, -0.1, 0.1)
        nn.init.uniform_(self.u_omega, -0.1, 0.1)

    def forward(self, inputs):
        # inputs的形状是(seq_len,batch_size)
        embeddings = self.word_embeddings(inputs)
        # 提取词特征,输出形状为(seq_len,batch_size,embedding_dim)
        # rnn.LSTM只返回最后一层的隐藏层在各时间步的隐藏状态。
        outputs, _ = self.encoder(embeddings)  # output, (h, c)
        # outputs形状是(seq_len,batch_size, 2 * num_hiddens)
        x = outputs.permute(1, 0, 2)
        # x形状是(batch_size, seq_len, 2 * num_hiddens)
        
        # Attention过程
        u = torch.tanh(torch.matmul(x, self.w_omega))
       # u形状是(batch_size, seq_len, 2 * num_hiddens)
        att = torch.matmul(u, self.u_omega)
       # att形状是(batch_size, seq_len, 1)
        att_score = F.softmax(att, dim=1)
       # att_score形状仍为(batch_size, seq_len, 1)
        scored_x = x * att_score
       # scored_x形状是(batch_size, seq_len, 2 * num_hiddens)
        # Attention过程结束
        
        feat = torch.sum(scored_x, dim=1) #加权求和
       # feat形状是(batch_size, 2 * num_hiddens)
        outs = self.decoder(feat)
       # out形状是(batch_size, 2)
        return outs
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14
  • 15
  • 16
  • 17
  • 18
  • 19
  • 20
  • 21
  • 22
  • 23
  • 24
  • 25
  • 26
  • 27
  • 28
  • 29
  • 30
  • 31
  • 32
  • 33
  • 34
  • 35
  • 36
  • 37
  • 38
  • 39
  • 40
  • 41
  • 42
  • 43
  • 44
  • 45
  • 46
  • 47
  • 48

LSTM部分

  • input size为(seq_len,batch_size),LSTM默认将序列长度(seq_len)作为第一维(由torchtext得到的batch就seq_len就是在第一维的)。embeddinng后size为(seq_len,batch_size, embedding_dim)。
  • 经过Bi-LSTM编码后,outputs size为(seq_len,batch_size, 2 * num_hiddens)。

Attention 部分
公式如下:
在这里插入图片描述
注意力说白了就是加权求和(有的可能是只加权不求和)。权重怎么来的呢?计算向量之间的相似度。我们都知道原始的注意力里有Q、K、V。V可以省略,重点是K和Q。K就是自己,Q就是别人。通过让Q和K中的每一个向量计算相似度,得到不同的权重(相似度越大权重越大),然后给K中的每一个向量加权。
现在问题来了,如果要对文本做注意力,文本自身就是K,哪来的Q呢。这里的Q和K就是相同的。你可以这么算,另外一种方法就是《 Hierarchical Attention Networks for Document Classification》提出来的,也是上文我们实现的代码。
不是没有Q吗?我们就随机初始化一个Q,把它作为context vector,让它去代表整个句子的语义。然后让它和句子中每个向量相乘,得到权重。然后再加权求和。
好了,下面解释公式。
首先将 h i t h_{it} hit(隐藏向量)输入到单层神经网络(代码中省略了 b w b_{w} bw)得到 u i t u_{it} uit,然后让 u i t u_{it} uit的转置和 u w u_{w} uw(context vector)相乘再经过 s o f t m a x softmax softmax归一化得到权重 α i t \alpha _{it} αit。最后让 α i t \alpha _{it} αit h i t h_{it} hit相乘并求和得到加权后的向量表示 s i s_{i} si。(这里的第一步就是做了个线性变换。)
代码中的w_omega( W w W_{w} Ww)和u_omega( u w u_{w} uw)都是随机初始化的。

完整代码在这里:
https://github.com/WHLYA/text-classification.
实验结果:
LSTM
在这里插入图片描述
LSTM+Attention:
在这里插入图片描述
加了Attention后准确率提升了一点。

声明:本文内容由网友自发贡献,不代表【wpsshop博客】立场,版权归原作者所有,本站不承担相应法律责任。如您发现有侵权的内容,请联系我们。转载请注明出处:https://www.wpsshop.cn/w/花生_TL007/article/detail/695995
推荐阅读
相关标签
  

闽ICP备14008679号