如何在张量流顺序模型中添加CRF层?

Sai*_*ava 5 python-3.x crf tf.keras tensorflow2.0

我正在尝试在 TensorFlow 顺序模型中实现 CRF 层来解决 NER 问题。我不知道该怎么做。以前,当我实现 CRF 时,我使用 keras 中的 CRF 和 TensorFlow 作为后端,即我在 keras 而不是 TensorFlow 中创建了整个模型,然后通过 CRF 传递整个模型。有效。

But now I want to develop the model in Tensorflow as tensorflow2.0.0 beta already has keras inbuilt in it and I am trying to build a sequential layer and add CRF layer after a bidirectional lstm layer. Although I am not sure how to do that. I have gone through the CRF documentation in tensorflow-addons and it contains different functions such as forward CRF etc etc but not sure how to implement them as a layer ? I am wondering is it possible at all to implement a CRF layer inside a sequential tensorflow model or do I need to build the model graph from scratch and then use CRF functions ? Can anyone please help me with it. Thanks in advance

Ler*_*ang 3

在此输入图像描述

在训练过程中:

您可以参考这个API:

tfa.text.crf_log_likelihood(
    inputs,
    tag_indices,
    sequence_lengths,
    transition_params=None
)
Run Code Online (Sandbox Code Playgroud)

输入是一元势(就像逻辑回归中的那样,您可以参考这个答案),在您的情况下,它们是 logits(通常不是 softmax 激活函数之后的分布)或状态BiLSTM 用于编码器中的每个字符(上图中的 P1、P2、P3、P4;)。

tag_indices是目标标签索引,sequence_lengths表示批次中的序列长度。

Transition_params 是二元势(也是标签如何从一个时间步过渡到下一个时间步),您可以自己创建矩阵,也可以让 API 为您创建矩阵。

在推理过程中:
您只需使用此 API:

tfa.text.viterbi_decode(
    score,
    transition_params
) 
Run Code Online (Sandbox Code Playgroud)

分数代表与训练中相同的输入(P1、P2、P3、P4 状态),transition_params 也是在训练过程中训练的。