【发布时间】:2021-05-04 22:18:53
【问题描述】:
我正在尝试为 NER 任务实现 BiLSTM-Attention-CRF 模型。我能够基于 BILSTM-CRF 模型(代码来自 here)执行 NER 任务,但我需要注意提高模型的性能。
现在我的模型是:
BiLSTM -> 线性层(隐藏到标签) -> CRf 层
线性层的输出是(序列长度 x 标记集大小),然后将其馈送到 CRF 层。
我正在尝试使用以下代码将线性层替换为注意力层:
class SelfAttention(nn.Module):
def __init__(self, hidden_dim):
super().__init__()
self.hidden_dim = hidden_dim
self.projection = nn.Sequential(
nn.Linear(hidden_dim, 64),
nn.ReLU(True),
nn.Linear(64, 1)
)
def forward(self, encoder_outputs):
batch_size = encoder_outputs.size(0)
# (B, L, H) -> (B , L, 1)
energy = self.projection(encoder_outputs)
weights = F.softmax(energy.squeeze(-1), dim=1)
# (B, L, H) * (B, L, 1) -> (B, H)
outputs = (encoder_outputs * weights.unsqueeze(-1)).sum(dim=1)
return outputs, weights
这样做时我有两个问题:
- 我不能让它工作,所以输出应该是(seq.length x tagset size)的形状,这样它就可以被送入CRF层。
- 根据这个paper,我们需要初始化和学习我在注意力模型的这个实现中看不到的词级上下文向量。
请帮帮我。
TIA
【问题讨论】:
标签: python pytorch named-entity-recognition attention-model